/**
 * 地图平台基础类库
 * @author 陈浩
 * @date 2015-05-22
 */
/**
 * gd_data_version 高德边界版本
 */
var gd_data_version;
var BMAP_ANCHOR_TOP_LEFT = 1;//控件将定位到地图的左上角
var BMAP_ANCHOR_TOP_RIGHT = 2;//控件将定位到地图的右上角
var BMAP_ANCHOR_BOTTOM_LEFT = 3;//控件将定位到地图的左下角
var BMAP_ANCHOR_BOTTOM_RIGHT = 4;//控件将定位到地图的右下角
/**
 * 获得项目路径
 * @return
 */
var _prejoctUrl = 'optimoveAppAddress';
var _geoserverUrl = 'geoserverAppAddress';
function getRootPath() {
    var curWWWPath = window.location.href;
    var pathName = window.location.pathname;
    var pos = curWWWPath.indexOf(pathName);
    var localhostPath = curWWWPath.substring(0, pos);
    var porejectName = pathName.substring(0, pathName.substring(1).indexOf('/') + 1);
    return (localhostPath + porejectName);
}
/**
 * 获取高德地图边界版本号
 */
function getDistrictVersion() {
    if (!gd_data_version) {
        $.ajax({
            url: getRootPath() + "/modelattributes/map/getDistrictVersion.do",
            async: false,
            cache: false,
            //dataType : "jsonp",
            type: "post",
            data: {},
            success: function (_data) {
                var storage = window.localStorage;
                if (storage) {
                    //	storage.clear();
                }
                if (typeof _data === 'string') {
                    _data = jQuery.parseJSON(_data);
                }
                if (_data.result == 'ok') {
                    gd_data_version = _data.data;
                    var storage = window.localStorage;
                    if (storage) {
                        var oldVersion = storage.getItem('gd_data_version');
                        if (!oldVersion || gd_data_version != oldVersion) {
                            storage.clear();
                            storage.setItem('gd_data_version', gd_data_version);
                        }
                    }
                } else {
                    alert("获得高德边界数据版本出错[" + _data.errorMsg + "]");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("异常:获得高德边界数据版本出错" + textStatus);
            }
        });
    }
    return gd_data_version;
}


(function (a) {


    window.drawManagerGaoUrl = 'gateWayAddressnbcbimages';
    window.productUrlWebRoot = 'optimoveAppAddress'; //main.js中替换url
    window.gaodeProvider = 'gaode';
    //是否已经引入高德Heatmap库,挂载到网页window下
    var HeatmapLoaded = { 'isHeatmapLoaded': false };
    window.HeatmapLoaded = HeatmapLoaded;
    //是否已经引入高德RangingTool库,挂载到网页window下
    var RangingToolLoaded = { 'isRangingToolLoaded': false };
    window.RangingToolLoaded = RangingToolLoaded;
    //是否已经加载搜索联想模块
    var AutocompleteLoaded = { 'isAutocompleteLoaded': false };
    window.AutocompleteLoaded = AutocompleteLoaded;
    //是否已经加载POI搜索模块
    var PlaceSearchLoaded = { 'isPlaceSearchLoaded': false };
    window.PlaceSearchLoaded = PlaceSearchLoaded;
    //是否已经加载点聚合模块
    var MarkerClustererLoaded = { 'isMarkerClustererLoaded': false };
    window.MarkerClustererLoaded = MarkerClustererLoaded;
    //是否已经引入高德Walking库,挂载到网页window下
    var WalkingLoaded = { 'isWalkingLoaded': false };
    window.WalkingLoaded = WalkingLoaded;
    //是否已经引入高德Driving库,挂载到网页window下
    var DrivingLoaded = { 'isDrivingLoaded': false };
    window.DrivingLoaded = DrivingLoaded;
    //是否已经引入高德Driving库,挂载到网页window下
    var TransferLoaded = { 'isTransferLoaded': false };
    window.TransferLoaded = TransferLoaded;

    /**
     * 地图核心类库
     */
    function MapCore(container, MapOptions) {
        this.provider = "providertmp";													//地图供应商
        this.key = "keytmp";															//地图key
        if (MapOptions == undefined) {
            MapOptions = {};
            MapOptions.enableMapClick = false;
        }
        if (MapOptions != undefined && MapOptions.enableMapClick == undefined) {
            MapOptions.enableMapClick = false;
        }
        MapOptions.viewMode = "3D";//开启3D视图,默认为关闭
        this.map = new AMap.Map(container, MapOptions);												//高德地图对象
        this.mapDivId = container;
        this.zoom;																		//缩放级别
        this.centerPoint;																//中心点
        this.meMapValue = {};																//存放方法值  通过getMeMapValue(方法名称获得)  removeMeMapValue(方法名称进行删除)
        this.trafficLayer;																//实施路况图层
        this.mapType = 'gaode';
        this.prejoctUrl = 'optimoveAppAddress';
        this.nginxUrl = 'gateWayAddress';
        this.nginxImage = 'gateWayAddressnbcbimages';
        this.uploadImageUrl = '_UPLOAD_IMAGE_URL';
        this.cityRect = {
            minLng: 9999,
            maxLng: 0,
            minLat: 9999,
            maxLat: 0
        };
        this.heatmap = {};    																//热力图
        this._HeatmapLoaded = HeatmapLoaded;
        this._RangingToolLoaded = RangingToolLoaded;
        this.ruler = {};
        this._placeSearch = {}																//poi检索工具，默认只有一个
        this.mapTracks = [];
        this.cluster = [];																//高德聚合点对象集合
        this.walking = {};
        this.driving = {};
        this.transfer = {};
        this.resultJson = [];       // 存放画图返回的json数组
        this.overlays = [];
    }

    /**
     * 地图类的成员方法
     */
    MapCore.prototype = {
        constructor: MapCore,															//地图构造方法
        enableZoom: function (flag) {														//启用缩放
            this.map.setStatus({ zoomEnable: flag });
            // this.map.j.zoomEnable = flag;
        },
        setCenterAndZoom: function (centerPoint, zoom) {									//定位
            if (typeof centerPoint != "string") {
                this.centerPoint = centerPoint;
                this.zoom = zoom;
                this.map.setZoomAndCenter(this.zoom, this.centerPoint);
            }
        },
        panTo: function (Point) {															//将地图的中心点更改为给定的点
            //this.map.panTo(Point);
        },
        panBy: function (x, y, option) {

        },
        addControls: function(){
        	  this.map.viewMode= "3D";
        	  map.addControl(new AMap.ControlBar({
        		    showZoomBar:false,
        		    showControlButton:true,
        		    position:{
        		      right:'10px',
        		      top:'10px'
        		    }
        		  }));
        },
        goPan: function (point) {													//将地图的中心点更改为给定的点
            this.map.panTo([point.lon, point.lat]);
        },
        getCenter: function () {
            return this.map.getCenter();											//获取地图当前中心点
        },
        setCenter: function (Point) {													//设置中心点
            this.map.setCenter(Point);
        },
        addMarker: function (marker) {													//添加标志
            marker.setMap(this.map);
        },
        getZoom: function () {													//返回当前缩放级别
            return this.map.getZoom();
        },
        setZoom: function (zoomNum) {													//重新设置地图级别
            this.map.setZoom(zoomNum);
        },
        setMarkerIcon: function (marker, vicon) {											//添加标记的图标
            if (marker != undefined && vicon != undefined) {
                marker.setIcon(vicon);
            }

        },
        lngLatToContainer: function (lnglat) {                                         //经纬度转容器像素
            return this.map.lngLatToContainer(lnglat);
        },
        addEventMapListener: function (callname, callback) {                          //添加监听
            var listener = AMap.event.addListener(this.map, callname, callback, false);
            return listener
        },
        removeEventMap: function (listener) {                 //移除listener的监听
            AMap.event.removeListener(listener);
        },
        //set marker offset
        setMarkerOffset: function (marker, voffset) {
            if (marker != undefined && voffset != undefined) {
                marker.setOffset({ offset: voffset });
            }
        },
        addCircleMarker: function (options) {        //高德圆点标记

            var circleMarker = new AMap.CircleMarker({
                center: options.center,
                radius: options.radius,
                strokeColor: options.strokeColor || 'white',
                strokeWeight: options.strokeWeight || 2,
                strokeOpacity: options.strokeOpacity || 0.5,
                fillColor: options.fillColor || 'rgba(0,0,255,1)',
                fillOpacity: options.fillOpacity || '0.5',
                zIndex: options.zIndex || 10,
                bubble: options.bubble || true,
                cursor: 'pointer',
                clickable: true
            });
            return circleMarker;
        },
        addCircleMarkerListener: function (overlay, callbackName, callback) {
            var listener = AMap.event.addListener(overlay, callbackName, callback);
            return listener;
        },
        removeCircleMarkerListener: function (listener) {
            AMap.event.removeListener(listener);
        },
        addControl: function (object) {													//地图添加控件
            if (object != null) {
                this.map.addControl(object);
            }
        },
        setFeatures: function (value) {
            this.map.setFeatures(value);
        },
        setMapStyle: function (style) {
            this.map.setMapStyle(style);
        },
        addMapTypeControl: function () {
            var myMap = this.map;
            myMap.plugin(["AMap.MapType"], function () {
                var mapType = new AMap.MapType();
                myMap.addControl(mapType);
            });
        },
        addScaleControl: function () {													//设置比例尺
            var myMap = this.map;
            myMap.plugin(["AMap.Scale"], function () {
                var scale = new AMap.Scale();
                myMap.addControl(scale);
                scale.show();
            });
        },
        addOverviewMapControl: function () {												//设置鹰眼图
            var myMap = this.map;
            myMap.plugin(["AMap.OverView"], function () {
                var overView = new AMap.OverView();
                myMap.addControl(overView);
            });
        },
        addNavigationControl: function () {												//设置地图工具条
            var myMap = this.map;
            myMap.plugin(["AMap.ToolBar"], function () {
                var toolBar = new AMap.ToolBar();
                myMap.addControl(toolBar);
                toolBar.show();
            });
        },
        createTrack: function (options) {												//新增轨迹对象
            var mapTrack = new AMapLib.MapTrack(this.map, options);
            this.mapTracks.push(mapTrack);
            return this.mapTracks[this.mapTracks.length - 1];
        },
        removeTrack: function (index) {												//删除某个轨迹对象
            if (typeof index === "number" && index % 1 === 0) { // 判断为整数
                if (index >= 0 && index < this.mapTracks.length) {
                    if (!$.isEmptyObject(this.mapTracks[index].getPathSimplifier())) {
                        this.mapTracks[index].getPathSimplifier().setData([]);
                    }
                }
            }
        },
        removeAllTracks: function () {												//删除所有轨迹对象
            for (var i = 0; i < this.mapTracks.length; i++) {
                if (!$.isEmptyObject(this.mapTracks[i].getPathSimplifier())) {
                    this.mapTracks[i].getPathSimplifier().setData([]);
                }
            }
        },
        createAnimationTrack: function (map, options) {

            //创建轨迹动画
            var animationTrack = new AMapLib.AnimationTrack(map, options);
            return animationTrack;
        },
        queryAccessTrack: function (map, options) {   //非访客轨迹驻留计算
            var opt = options || {};
            var data = opt['data'] || [];
            var minRemain = opt['minRemain'] || 20;
            var radius = opt['radius'] || 100;
            var startImage = opt['startImage'] || this.nginxImage + '/upload/f51622f4-1b57-480d-897b-44b97c342a75.png';
            var endImage = opt['endImage'] || this.nginxImage + '/upload/531d8433-14c8-4391-975a-224de24e86b1.png';
            var startoffset = opt['startoffset'] || new MapCore.Pixel([-15, -30]);
            var endoffset = opt['endoffset'] || new MapCore.Pixel([-15, -30]);
            var callback = opt['callback'] || function (marker, sDate, eDate, howLong) {
                //  2.设置信息窗口
                marker.setInfoWindow("<div class='info'>驻留时间:" + sDate + "~" + eDate + "</div>" +
                    "<div>驻留时长:" + howLong + "分钟</div>");
            };
            for (var i = 0; i < data.length; i++) {  //重组传入的数据   [支持多个轨迹]
                var d = [];
                var path = data[i].path;
                for (var k = 0; k < path.length; k++) {
                    var track = {
                        x: path[k][0],
                        y: path[k][1],
                        time: path[k][2]
                    };
                    d.push(track)
                }
                console.log(d);
                if (d.length != 0) {
                    var startPoint = new MapCore.Point([d[0].x, d[0].y]);
                    console.log(startPoint)
                    var startMark = new MapCore.Marker({
                        autoOptions: 1,
                        point: startPoint,
                        icon: new MapCore.Icon({
                            image: startImage
                        }),
                        offset: startoffset
                    });
                    map.addOverlay(startMark);
                    var endPoint = new MapCore.Point([d[d.length - 1].x, d[d.length - 1].y]);
                    console.log(endPoint)
                    var endMark = new MapCore.Marker({
                        autoOptions: 1,
                        point: endPoint,
                        icon: new MapCore.Icon({
                            image: endImage
                        }),
                        offset: endoffset
                    });
                    map.addOverlay(endMark);
                    var accessTrackRemain = new AMapLib.AccessTrackRemain(map, opt);
                    accessTrackRemain.setPositionList(d);  //传入时间排序的（参考d）
                    var stayPoints = accessTrackRemain.getPositionListStayPoints(minRemain, radius);  //最短驻留时间（分钟），半径（米）
                    accessTrackRemain.setAccessTrackLabel(stayPoints, callback);   // 绘制非访客驻留区域
                }
            }
        },
        getAnimationTrackData: function (json) {								//获取轨迹数据
            var url = json.url;
            var data = JSON.stringify(json.data);
            var callback = json.callback;
            $.ajax({
                cache: 'false',
                url: url,
                type: "post",
                dataType: 'json', //指定服务器返回的数据类型
                data: data,
                contentType: 'application/json;charset=UTF-8',
                success: callback
            });
        },
        setCluster: function (markers, options, callback) {													//聚合点
            var myMap = this.map;
            var that = this;
            var markerClusterer;
            if (arguments.length == 1 || (arguments.length == 2 && typeof arguments[1] == "function")) { // 未提供配置参数
                if (!window.MarkerClustererLoaded.isMarkerClustererLoaded) {
                    window.MarkerClustererLoaded.isMarkerClustererLoaded = true;
                    AMap.plugin(["AMap.MarkerClusterer"], function () {
                        markerClusterer = new AMap.MarkerClusterer(myMap, markers);
                        markerClusterer.setMaxZoom(16);
                        that.cluster.push(markerClusterer);
                        if (!!options) {
                            options();
                        }
                    });
                } else {
                    markerClusterer = new AMap.MarkerClusterer(myMap, markers);
                    markerClusterer.setMaxZoom(16);
                    that.cluster.push(markerClusterer);
                    if (!!options) {
                        options();
                    }
                }

            } else if (arguments.length == 2 || arguments.length == 3) {
                var _options = {};
                if (options.drawtype == "icon") {
                    //图标必须指定图标样式
                    if (options.styles == undefined) {
                        return;
                    }
                    _options.styles = options.styles;
                } else if (options.drawtype == "auto") {
                    //通过回调函数自定义，回调函数默认样式如下  //判断回调函数是不是函数
                    if (options.renderClusterMarker == undefined || typeof options.renderClusterMarker != 'function') {
                        var count = markers.length;//marker的总数
                        //绘制的回调函数
                        _options.renderClusterMarker = function (context) {
                            var dOffset = 0;//在最大一层级zoom，聚合点偏移掉作为重复点的数字显示
                            var size = Math.round(30 + Math.pow(context.count / count, 1 / 5) * 20);
                            if (map.getZoom() > 16) {
                                //注意重复点不要重复绘制，用map去重
                                var pointMap = {};
                                for (var i = 0; i < context.markers.length; i += 1) {
                                    var _marker = context.markers[i];
                                    if (pointMap[_marker.getPosition()] == undefined) {
                                        _marker.setMap(map);
                                        //支持自定义图标
                                        if (options._markerOptions != undefined) {
                                            var _opts = options._markerOptions;
                                            //如果显示label
                                            if (_opts.labelOptions && _opts.labelOptions.baseJson) {
                                                var _labelOptions = _opts.labelOptions;
                                                var _label = new MapCore.Label(_labelOptions.baseJson);
                                                //如果有labelStyle
                                                if (_labelOptions.styles) {
                                                    _label.setStyles(_labelOptions.styles);
                                                }
                                                if (_marker.labelContent) {
                                                    _label.setContent(_marker.labelContent);
                                                }
                                                _marker.setLabel(_label);
                                            }
                                            //如果自定义icon
                                            if (_opts.icon != undefined) {
                                                _marker.setIcon(_opts.icon);
                                            }
                                        }
                                        //记录重复点
                                        pointMap[_marker.getPosition()] = "1";
                                    }
                                }
                                //到最后一层级的时候，偏移掉聚合的图标，作为该点重复的数量
                                size = 20;
                                dOffset = -26;
                            }

                            var factor = Math.pow(context.count / count, 1 / 18);
                            var div = document.createElement('div');
                            var Hue = 180 - factor * 180;
                            var bgColor = 'hsla(' + Hue + ',100%,50%,0.7';
                            var fontColor = 'hsla(' + Hue + ',100%,20%,1';
                            var borderColor = 'hsla(' + Hue + ',100%,40%,1';
                            var shadowColor = 'hsla(' + Hue + ',100%,50%,1';
                            div.style.backgroundColor = bgColor;

                            div.style.width = div.style.height = size + 'px';
                            div.style.border = 'solid 1px ' + borderColor;
                            div.style.borderRadius = size / 2 + 'px';
                            div.style.boxShadow = '0 0 1px ' + shadowColor;
                            div.innerHTML = context.count;
                            div.style.lineHeight = size + 'px';
                            div.style.colot = fontColor;
                            div.style.fontSize = '14px';
                            div.style.textAlign = 'center';
                            context.marker.setOffset(new AMap.Pixel(-size / 2 + dOffset, -size / 2 + dOffset));
                            context.marker.setContent(div);
                        }
                    } else {
                        _options.renderClusterMarker = options.renderClusterMarker;
                    }
                } else {
                    //未匹配选项
                }

                if (!window.MarkerClustererLoaded.isMarkerClustererLoaded) {
                    window.MarkerClustererLoaded.isMarkerClustererLoaded = true;
                    AMap.plugin(["AMap.MarkerClusterer"], function () {
                        markerClusterer = new AMap.MarkerClusterer(myMap, markers, _options);
                        that.cluster.push(markerClusterer);
                        if (!!callback) {
                            callback();
                        }
                    });
                } else {
                    markerClusterer = new AMap.MarkerClusterer(myMap, markers, _options);
                    that.cluster.push(markerClusterer);
                    if (!!callback) {
                        callback();
                    }
                }
            }
        },
        clearMarkers: function (MarkerClusterer) {                                 //清除点聚合，老的方法，不建议新功能使用
            MarkerClusterer = this.map.cluster;
            if (MarkerClusterer != undefined) {
                MarkerClusterer.clearMarkers();
            }
        },
        removeAllClusterers: function () {                                        //清除点聚合
            for (var i = 0; i < this.cluster.length; i++) {
                this.cluster[i].clearMarkers();
            }
            this.cluster.splice(0, this.cluster.length);
        },

        getContainer: function () {                                                        //得到地图容器
            return this.map.getContainer();
        },
        getMarker: function (Point) {													//根据坐标获得Marker
            var allOverlay = this.map.getAllOverlays();
            for (var i = 0; i < allOverlay.length; i++) {
                if (allOverlay[i].getPosition() != null) {
                    if (allOverlay[i].getPosition().lng == Point.lng && allOverlay[i].getPosition().lat == Point.lat) {
                        return allOverlay[i];
                    }
                }
            }
        },
        addDrawingManager: function (fn, style) {
            var jsonObj = {};
            if (typeof fn === 'function') {
                jsonObj.drawingFun = fn;
            } else {
                if (fn) {
                    jsonObj = fn;
                }
            }
            if (!style) {
                style = {};
            }

            var key = 'addDrawingManager';
            var meMap = this;
            var mouseTool = null;
            // var overlays = [];


            var moveDiv = "<div id=\"move\" style=\"position: relative; float:left;background-color:rgb(255, 255, 255);padding: 0px;margin: 0px;margin-left；10px;border-color: gray;border-width: 1px;border-style: solid;border-top-left-radius: 5px;border-bottom-left-radius: 5px;width: 39px;height: 28.2px;\"><img id='moveImg' src=\"optimoveAppAddress/optimove/img/move.png\" width='100%' height='100%' style=\"border-top-left-radius: 5px;border-bottom-left-radius: 5px;\">"
                + "</div>";

            var polygonDiv = "<div id=\"polygon\" style=\"position: relative; float:left;background-color:rgb(255, 255, 255);padding: 0px;margin: 0px;margin-left；10px;border-color: gray;border-width: 1px;border-style: solid;width: 39px;height: 28.2px;\"><img id='polygonImg' src=\"optimoveAppAddress/optimove/img/polygon.png\" width='100%' height='100%'>"
                + "</div>";
            var yuanDiv = "<div id=\"yuan\" style=\"position: relative;float:left;background-color:rgb(255, 255, 255);padding: 0px;margin: 0px;border-color: gray;border-width: 1px;border-style: solid;width: 39px;height: 28.2px;\">"
                + "<img id='yuanImg' src=\"optimoveAppAddress/optimove/img/circle.png\" width='100%' height='100%'>"
                + "</div>";

            var polylineDiv = "<div id=\"polyline\" style=\"position: relative;float:left;background-color:rgb(255, 255, 255);padding: 0px;margin: 0px;border-color: gray;border-width: 1px;border-style: solid;width: 39px;height: 28.2px;\">"
                + "<img id='polylineImg' src=\"optimoveAppAddress/optimove/img/polyline.png\" width='100%' height='100%'>"
                + "</div>";

            var rectangleDiv = "<div id=\"rectangle\" style=\"position: relative;float:left;background-color:rgb(255, 255, 255);padding: 0px;margin: 0px;border-color: gray;border-width: 1px;border-style: solid;width: 39px;height: 28.2px;\">"
                + "<img id='rectangleImg' src=\"optimoveAppAddress/optimove/img/rectangle.png\" width='100%' height='100%'>"
                + "</div>";
            var circleExDiv = "<div id=\"circleEx\" style=\"position: relative;float:left;background-color:rgb(255, 255, 255);padding: 0px;margin: 0px;border-color: gray;border-width: 1px;border-style: solid;width: 39px;height: 28.2px;\">"
                + "<img id='circleExImg' src=\"optimoveAppAddress/optimove/map/draw/circleEx1.png\" width='100%' height='100%'>"
                + "</div>";
            var clearLastDiv = '<div id="clearLastDiv" style="width: 100px;height: 25.2px;position: relative;float:left;cursor: pointer; padding: 0px; text-align:center; padding-top: 3px;color: rgb(0, 153, 255);font-weight: bold; background-color: rgb(255, 255, 255); border: 1px solid gray; "'
                + ' >清除上一个</div>';
            var clearAllDiv = '<div id="clearAllDiv" style="width: 100px;height: 25.2px;position: relative;float:left;cursor: pointer; padding: 0px; text-align:center; padding-top: 3px;color: rgb(0, 153, 255);font-weight: bold; background-color: rgb(255, 255, 255);border-top-right-radius: 5px; border-bottom-right-radius: 5px; border: 1px solid gray; "'
                + ' >清除所有</div>';
            var x = style.offsetX && style.offsetX != 0 ? style.offsetX : 0;
            var y = style.offsetY && style.offsetY != 0 ? style.offsetY : 0;
            /*var tool = "<div id='me_mouse_tool' style='position: absolute;left: "+x+"px;top: "+y+"px;'></div>";
			 $(tool).append(div).append(yuanDiv).append(closeDiv).appendTo("#"+this.mapDivId);*/
            //搜索栏
            var tool = "<div id='me_mouse_tool'></div>";
            this.createMeControl({
                anchor: BMAP_ANCHOR_TOP_RIGHT,
                x: x,
                y: y,
                html: '<div  id="me_mouse_tool">' + $(tool).append(moveDiv).append(yuanDiv).append(polygonDiv).append(polylineDiv).append(rectangleDiv).append(circleExDiv).append(clearLastDiv).append(clearAllDiv).html() + '</div>'
            });
            /**/
            meMap.map.plugin(["AMap.MouseTool"], function () {
                mouseTool = new AMap.MouseTool(meMap.map);

                $('#clearLastDiv').click(function (e) {
                    if (meMap.overlays.length !== 0) {
                        meMap.map.remove(meMap.overlays[meMap.overlays.length - 1]);
                        meMap.resultJson.pop();
                        meMap.overlays.pop();
                    }
                    if (jsonObj.drawingFun) {
                        jsonObj.drawingFun(meMap.resultJson, meMap.overlays);
                    }
                });

                $('#clearAllDiv').click(function (e) {
                    if (!jsonObj.isNoRunClose) {
                        for (var i = 0; i < meMap.overlays.length; i++) {
                            meMap.map.remove(meMap.overlays[i]);
                        }
                        // map.clearOverlays();
                        mouseTool.close();
                    }
                    meMap.resultJson.length = 0;
                    meMap.resultJson = [];
                    meMap.overlays.length = 0;
                    if (jsonObj.drawingFun) {
                        jsonObj.drawingFun(meMap.resultJson, meMap.overlays);
                    }
                });
                var tempDrawListener;

                // 拖动地图
                AMap.event.addDomListener(document.getElementById('move'), 'click', function () {
                    // 切换图片路径实现显示点击效果
                    $('#moveImg').attr('src', "optimoveAppAddress/optimove/img/move_select.png");
                    $('#yuanImg').attr('src', "optimoveAppAddress/optimove/img/circle.png");
                    $('#polygonImg').attr('src', "optimoveAppAddress/optimove/img/polygon.png");
                    $('#polylineImg').attr('src', "optimoveAppAddress/optimove/img/polyline.png");
                    $('#rectangleImg').attr('src', "optimoveAppAddress/optimove/img/rectangle.png");
                    $('#circleExImg').attr('src', "optimoveAppAddress/optimove/map/draw/circleEx1.png");

                    if (tempDrawListener) {
                        mouseTool.close();
                        AMap.event.removeListener(tempDrawListener);
                    }
                }, false);

                AMap.event.addDomListener(document.getElementById('polygon'), 'click', function () {
                    // 切换图片路径实现显示点击效果
                    $('#moveImg').attr('src', "optimoveAppAddress/optimove/img/move.png");
                    $('#yuanImg').attr('src', "optimoveAppAddress/optimove/img/circle.png");
                    $('#polygonImg').attr('src', "optimoveAppAddress/optimove/img/polygon_select.png");
                    $('#polylineImg').attr('src', "optimoveAppAddress/optimove/img/polyline.png");
                    $('#rectangleImg').attr('src', "optimoveAppAddress/optimove/img/rectangle.png");
                    $('#circleExImg').attr('src', "optimoveAppAddress/optimove/map/draw/circleEx1.png");
                    if (tempDrawListener) {
                        mouseTool.close();
                        AMap.event.removeListener(tempDrawListener);
                    }
                    mouseTool.polygon();
                    var drawListener = AMap.event.addListener(mouseTool, 'draw', function (e) {
                        // meMap.overlays.push(e.obj);
                        // var str = {"type": "polygon", "point": e.obj.getPath().toString(), "provider": "gaode"};
                        // meMap.resultJson.push(str);
                        // if (jsonObj.drawingFun) {
                        //     jsonObj.drawingFun(meMap.resultJson);
                        // }
                        // meMap.setMeMapValue(key, str);
                        // AMap.event.removeListener(drawListener);
                        addDraw("polygon", e.obj);

                        meMap.map.plugin(['AMap.PolyEditor'], function () {
                            var polyEditor = new AMap.PolyEditor(meMap.map, e.obj);
                            addEdit("polygon", polyEditor, e.obj);
                            //callback("polygon",polyEditor,e.obj);
                        });

                    }, false);
                    tempDrawListener = drawListener;
                }, false);
                AMap.event.addDomListener(document.getElementById('yuan'), 'click', function () {

                    $('#moveImg').attr('src', "optimoveAppAddress/optimove/img/move.png");
                    $('#yuanImg').attr('src', "optimoveAppAddress/optimove/img/circle_select.png");
                    $('#polygonImg').attr('src', "optimoveAppAddress/optimove/img/polygon.png");
                    $('#polylineImg').attr('src', "optimoveAppAddress/optimove/img/polyline.png");
                    $('#rectangleImg').attr('src', "optimoveAppAddress/optimove/img/rectangle.png");
                    $('#circleExImg').attr('src', "optimoveAppAddress/optimove/map/draw/circleEx1.png");
                    if (tempDrawListener) {
                        mouseTool.close();
                        AMap.event.removeListener(tempDrawListener);
                    }
                    mouseTool.circle();
                    var drawListener = AMap.event.addListener(mouseTool, 'draw', function (e) {
                        // meMap.overlays.push(e.obj);
                        // var getCircle = e.obj;
                        // //得到圆的中心点坐标(维度)
                        // /*var str = "lat="+getCircle.getCenter().lat+"&";
                        // 	//得到圆的中心点坐标(经度)
                        // 	str += "lng="+getCircle.getCenter().lng+"&";
                        // 	//圆半径
                        // 	str += "radius="+getCircle.getRadius()+"&";
                        // 	//地图服务商名
                        // 	str += "provider=gaode";*/
                        // var json = {
                        //     "type": "circle",
                        //     "point": {
                        //         "lat": getCircle.getCenter().lat,
                        //         "lng": getCircle.getCenter().lng,
                        //         "lon": getCircle.getCenter().lng,
                        //         "radius": getCircle.getRadius()
                        //     },
                        //     "provider": "gaode"
                        // };
                        // meMap.resultJson.push(json);
                        // if (jsonObj.drawingFun) {
                        //     jsonObj.drawingFun(meMap.resultJson);
                        // }
                        // meMap.setMeMapValue(key, json);
                        // AMap.event.removeListener(drawListener);
                        //$("#resultpoint").val(str);
                        addDraw("circle", e.obj);

                        meMap.map.plugin(['AMap.CircleEditor'], function () {
                            var polyEditor = new AMap.CircleEditor(meMap.map, e.obj);
                            addEdit("circle", polyEditor, e.obj);
                        });
                    }, false);
                    tempDrawListener = drawListener;
                }, false);
                // 画线
                AMap.event.addDomListener(document.getElementById('polyline'), 'click', function () {
                    console.info('polyline');

                    $('#moveImg').attr('src', "optimoveAppAddress/optimove/img/move.png");
                    $('#yuanImg').attr('src', "optimoveAppAddress/optimove/img/circle.png");
                    $('#polygonImg').attr('src', "optimoveAppAddress/optimove/img/polygon.png");
                    $('#polylineImg').attr('src', "optimoveAppAddress/optimove/img/polyline_select.png");
                    $('#rectangleImg').attr('src', "optimoveAppAddress/optimove/img/rectangle.png");
                    $('#circleExImg').attr('src', "optimoveAppAddress/optimove/map/draw/circleEx1.png");
                    if (tempDrawListener) {
                        mouseTool.close();
                        AMap.event.removeListener(tempDrawListener);
                    }
                    mouseTool.polyline();
                    var drawListener = AMap.event.addListener(mouseTool, 'draw', function (e) {
                        // meMap.overlays.push(e.obj);
                        // var str = {"type": "polyline", "point": e.obj.getPath().toString(), "provider": "gaode"};
                        // meMap.resultJson.push(str);
                        // if (jsonObj.drawingFun) {
                        //     jsonObj.drawingFun(meMap.resultJson);
                        // }
                        // meMap.setMeMapValue(key, str);
                        // AMap.event.removeListener(drawListener);
                        addDraw("polyline", e.obj);
                        meMap.map.plugin(['AMap.PolyEditor'], function () {
                            var polyEditor = new AMap.PolyEditor(meMap.map, e.obj);
                            addEdit("polyline", polyEditor, e.obj);
                        });
                    }, false);
                    tempDrawListener = drawListener;
                }, false);
                // 画矩形
                AMap.event.addDomListener(document.getElementById('rectangle'), 'click', function () {
                    console.info('rectangle');
                    $('#moveImg').attr('src', "optimoveAppAddress/optimove/img/move.png");
                    $('#yuanImg').attr('src', "optimoveAppAddress/optimove/img/circle.png");
                    $('#polygonImg').attr('src', "optimoveAppAddress/optimove/img/polygon.png");
                    $('#polylineImg').attr('src', "optimoveAppAddress/optimove/img/polyline.png");
                    $('#rectangleImg').attr('src', "optimoveAppAddress/optimove/img/rectangle_select.png");
                    $('#circleExImg').attr('src', "optimoveAppAddress/optimove/map/draw/circleEx1.png");

                    if (tempDrawListener) {
                        mouseTool.close();
                        AMap.event.removeListener(tempDrawListener);
                    }
                    mouseTool.rectangle();
                    var drawListener = AMap.event.addListener(mouseTool, 'draw', function (e) {
                        // meMap.overlays.push(e.obj);
                        // var str = {"type": "rectangle", "point": e.obj.getPath().toString(), "provider": "gaode"};
                        // meMap.resultJson.push(str);
                        // if (jsonObj.drawingFun) {
                        //     jsonObj.drawingFun(meMap.resultJson);
                        // }
                        // meMap.setMeMapValue(key, str);
                        // AMap.event.removeListener(drawListener);
                        addDraw("rectangle", e.obj);
                        meMap.map.plugin(['AMap.PolyEditor'], function () {
                            var polyEditor = new AMap.PolyEditor(meMap.map, e.obj);
                            addEdit("rectangle", polyEditor, e.obj);
                        });
                        // meMap.map.plugin(['AMap.RectangleEditor'], function () {
                        //     var polyEditor = new AMap.RectangleEditor(meMap.map, e.obj);
                        //     addEdit("rectangle", polyEditor, e.obj);
                        // });
                    }, false);
                    tempDrawListener = drawListener;
                }, false);

                // 画不规则图形
                AMap.event.addDomListener(document.getElementById('circleEx'), 'click', function () {
                    console.info('circleEx');
                    $('#moveImg').attr('src', "optimoveAppAddress/optimove/img/move.png");
                    $('#yuanImg').attr('src', "optimoveAppAddress/optimove/img/circle.png");
                    $('#polygonImg').attr('src', "optimoveAppAddress/optimove/img/polygon.png");
                    $('#polylineImg').attr('src', "optimoveAppAddress/optimove/img/polyline.png");
                    $('#rectangleImg').attr('src', "optimoveAppAddress/optimove/img/rectangle.png");
                    $('#circleExImg').attr('src', "optimoveAppAddress/optimove/map/draw/circleEx.png");
                    var options = jsonObj;
                    var container = this.mapDivId;
                    var drawingManager_gaode = new DrawingManager_gaode(meMap, options, container);
                    drawingManager_gaode._outerClickDrawing("circleEx");

                }, false);

                // 绘制添加方法
                function addDraw(type, plane) {
                    document.getElementById("move").click();
                    if (type == "circle") {
                        meMap.map.remove(plane);
                        var center = [Number(plane.getCenter().lng), Number(plane.getCenter().lat)];
                        var radius = plane.getRadius() / 1000;
                        if (radius == 0) {
                            return;
                        }
                        var options = {
                            steps: 50,
                            units: "kilometers",
                            properties: { foo: "bar" },
                        };
                        var circle = turf.circle(center, radius, options);
                        var jsonPoint = circle.geometry.coordinates[0];
                        var polygon = new AMap.Polygon({
                            path: jsonPoint,
                            strokeColor: '#00ae66',
                            strokeOpacity: 1,
                            fillColor: '#00ae66',
                            fillOpacity: 0.3,
                            enableClicking: false
                        });
                        meMap.addOverlay(polygon);
                        meMap.map.plugin(['AMap.PolyEditor'], function () {
                            var polyEditor = new AMap.PolyEditor(meMap.map, polygon);
                            addEdit("polygon", polyEditor, polygon);
                        });
                        meMap.overlays.push(polygon);
                        var json = {"type": "polygon", "point": polygon.getPath().toString(), "provider": "gaode"};
                        meMap.resultJson.push(json);
                        if (jsonObj.drawingFun) {
                            jsonObj.drawingFun(meMap.resultJson, meMap.overlays);
                        }
                        meMap.setMeMapValue(key, json);
                    } else {
                        // 面、线、矩形
                        meMap.overlays.push(plane);
                        var str = { "type": type, "point": plane.getPath().toString(), "provider": "gaode" };
                        meMap.resultJson.push(str);
                        if (jsonObj.drawingFun) {
                            jsonObj.drawingFun(meMap.resultJson, meMap.overlays);
                        }
                        meMap.setMeMapValue(key, str);
                    }

                }
                // 添加图形编辑菜单
                function addEdit(type, polyEditor, plane) {
                    var menu = new AMap.ContextMenu();
                    var txtMenuItem = [
                        {
                            text: '编辑',
                            callback: function () {
                                // console.log(plane);
                                polyEditor.open();
                            }
                        },
                        {
                            text: '关闭',
                            callback: function () {
                                // console.log(plane);
                                polyEditor.close();
                                addDraw(type, plane);
                            }
                        }
                    ];

                    for (var i = 0; i < txtMenuItem.length; i++) {
                        menu.addItem(txtMenuItem[i].text, txtMenuItem[i].callback || function () {
                        }, i);
                    }
                    plane.on('rightclick', function (e) {
                        menu.open(meMap.map, e.lnglat);
                    });

                }


            });


        },
        /**
         * 自定义控件
         * anchor:位置
         * x    :偏移位置
         * y    :偏移位置
         * html :显示代码
         * BMAP_ANCHOR_TOP_LEFT    控件将定位到地图的左上角
         BMAP_ANCHOR_TOP_RIGHT    控件将定位到地图的右上角
         BMAP_ANCHOR_BOTTOM_LEFT    控件将定位到地图的左下角
         BMAP_ANCHOR_BOTTOM_RIGHT    控件将定位到地图的右下角
         NavigationControl
         */
        createMeControl: function (json) {
            var map = this;
            json = json ? json : {};
            if (!json.anchor && json.anchor != 0) {
                json.anchor = BMAP_ANCHOR_TOP_RIGHT;
            }
            if (!json.x && json.x != 0) {
                json.x = 10;
            }
            if (!json.y && json.y != 0) {
                json.y = 10;
            }
            json.html = $(json.html)[0];
            var cls = '';
            var xStr = '';
            var yStr = '';
            switch (json.anchor) {
                case BMAP_ANCHOR_TOP_LEFT:
                    cls = 'ANCHOR_TOP_LEFT';
                    xStr = 'margin-left';
                    yStr = 'margin-top';
                    break;
                case BMAP_ANCHOR_TOP_RIGHT:
                    cls = 'ANCHOR_TOP_RIGHT';
                    xStr = 'margin-right';
                    yStr = 'margin-top';
                    break;
                case BMAP_ANCHOR_BOTTOM_LEFT:
                    cls = 'ANCHOR_BOTTOM_LEFT';
                    xStr = 'margin-left';
                    yStr = 'margin-bottom';
                    break;
                case BMAP_ANCHOR_BOTTOM_RIGHT:
                    cls = 'ANCHOR_BOTTOM_RIGHT';
                    xStr = 'margin-right';
                    yStr = 'margin-bottom';
                    break;
                default:
                    break;
            }
            var tool = "<div  class='" + cls + "' style='" + xStr + ": " + json.x + "px;" + yStr + ": " + json.y + "px;'></div>";
            var menuTool = $(tool);
            menuTool.append(json.html);
            menuTool.appendTo("#" + map.mapDivId);
            var meMap = this.map;
        },
        /**
         * 外部调用绘图工具
         */
        addDrawingManager_outer: function (fn) {
            var jsonObj = {};
            if (typeof fn === 'function') {
                jsonObj.drawingFun = fn;
            } else {
                if (fn) {
                    jsonObj = fn;
                }
            }
            var options = jsonObj;
            var container = this.mapDivId;
            //var drawingManager_gaode = new DrawingManager_gaode(meMap, options, container);
            this.drawingManager_gaode._outerClickDrawing(options.type);
        },
        clearDrawingManager_outer: function () {
            this.drawingManager_gaode._outerCloseDrawing();
        },

        //-----------------------add by hxp---------------------
        pixelToPoint: function (pixel) {
            return this.map.pixelToLngLat(pixel);
        },

        pointToPixel: function (point) {
            return this.map.lnglatToPixel(point);
        },
        buildPolyline: function (lng1, lat1, lng2, lat2, style) {
            var options = {
                path: [
                    new AMap.LngLat(lng1, lat1),
                    new AMap.LngLat(lng2, lat2)
                ]
            };
            for (key in style) {
                options[key] = style[key];
            }
            var polyline = new AMap.Polyline(options);

            return polyline;
        },
        //构造marker点
        buildMarkerPoints: function (pointsAry, img, handleClickPoint) {
            var _this = this;

            showMarkerPoint();

            function showMarkerPoint() {
                //浏览器端过滤
                var data = filterFromBrower(pointsAry);
                for (var i = 0; i < data.length; i++) {
                    var point = new MapCore.Point([data[i]["LONGITUDE"], data[i]["LATITUDE"]]);
                    var marker = new MapCore.Marker(point);
                    marker.addEvent("click", function (e) {
                        if (handleClickPoint) {
                            e.point = e.target.getPosition();
                            handleClickPoint(e.point);
                        }
                    });
                    marker.setIcon(img.src);
                    _this.addMarker(marker);
                }

            }

            //数据从后台查寻出来后，地图缩放拖动操作的过滤
            function filterFromBrower(data) {
                //边界
                var bounds = _this.getBounds();
                //过滤后的结果
                var filteredPoints = new Array();
                //判断是否处理过对象
                var object = new Object();

                for (var i = 0; i < data.length; i++) {
                    var point = data[i];
                    //相同经纬度会跳过此次循环
                    if (object[point.LONGITUDE + "," + point.LATITUDE] == null) {
                        object[point.LONGITUDE + "," + point.LATITUDE] = true;
                    } else {
                        continue;
                    }

                    //经纬度转像素点
                    var pixel = _this.pointToPixel(new AMap.LngLat(point["LONGITUDE"], point["LATITUDE"]));
                    //获取向左上角偏移后的经纬度
                    var coordSwift = _this.pixelToPoint(new AMap.Pixel(pixel.x - img.width / 2, pixel.y - img.height));

                    //点在边界内
                    if (bounds.contains(new AMap.LngLat(point["LONGITUDE"], point["LATITUDE"]))) {
                        filteredPoints.push(point);
                    }
                }
                return filteredPoints;
            }


        },

        //---------------add by ltq  20151117  start----------------//
        //		searchPrivateDataAtEX: function(modelcode,resultpoint,queryConditions,header,CallbankName,type){							//在地图上画圈条件检索
        //			if(modelcode== undefined||queryConditions== undefined){
        //				alert("参数不可为空！");
        //				return;
        //			}
        //			jQuery.support.cors = true;
        //			var searchByAnyModelData = "optimoveAppAddress/optimove/modelattributes/searchByAnyModelDataEX.do";
        //			var arrayList;
        //			$.getJSON(searchByAnyModelData,
        //			{
        //			    modelcode : modelcode,
        //				resultpoint:resultpoint,
        //				queryConditions : queryConditions,
        //				header : header,
        //				type:type
        //			},function(date,status,XMLHttpRequest){
        //				window[CallbankName](date);
        //
        //			}
        //
        //			);
        ////			$.ajax({
        ////				url : searchByAnyModelData,
        ////				async :true,
        ////				cache:false,
        ////				dataType : "jsonp",
        ////				type : "get",
        ////				data: {
        ////				    modelcode : modelcode,
        ////					resultpoint:resultpoint,
        ////					queryConditions : queryConditions,
        ////					header : header,
        ////					type:type
        ////				},
        ////				success : function(_data) {
        ////						window[CallbankName](_data);
        ////					},
        ////				error:function(XMLHttpRequest, textStatus, errorThrown){
        ////						//console.info(1111111);
        ////						if(XMLHttpRequest.status!=200)
        ////						alert("异常:"+XMLHttpRequest.status+";"+XMLHttpRequest.readyStatus+";"+textStatus);
        ////					}
        ////				});
        //			return arrayList;
        //		},

        searchPrivateDataAtEX: function (modelcode, resultpoint, queryConditions, header, CallbankName, type) {							//在地图上画圈条件检索
            if (modelcode == undefined || queryConditions == undefined) {
                alert("参数不可为空！");
                return;
            }
            mapPare.markersIndex = 0;
            mapPare.isShowMake = 0;
            jQuery.support.cors = true;
            var searchByAnyModelData = "optimoveAppAddress/optimove/modelattributes/searchByAnyModelDataEX_GD.do";
            var arrayList;
            for (var i = 2; i <= 8; i++) {
                $.ajax({
                    url: searchByAnyModelData,
                    async: true,
                    cache: false,
                    dataType: "jsonp",
                    jsonp: "jsonpcallback",
                    //jsonpCallback:CallbankName,				//jsonp的回调函数名
                    type: "get",
                    data: {
                        modelcode: modelcode,
                        resultpoint: resultpoint,
                        queryConditions: queryConditions,
                        header: header,
                        type: i
                    },
                    success: function (data) {
                        window[CallbankName](data);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("异常:" + XMLHttpRequest.status + ";" + XMLHttpRequest.readyStatus + ";" + textStatus);
                    }
                });
            }

            return arrayList;
        },


        dataToMarkers: function (data, ThisfieldName, fn) {													//将json数组转换成标注点集合
            if (data == undefined || ThisfieldName == undefined) {
                alert("参数不可为空！");
                return;
            }
            if (data.length == 0) {
                alert("没有要标注的地址");
                return;
            }
            if (data.length > 100000) {
                alert("取点数据大于10000条，请增加筛选条件");
                return;
            }
            var markers = [];
            var points = [];
            var centerPoint = new MapCore.Point([data[0]["LONGITUDE"], data[0]["LATITUDE"]]);
            for (var i = 0; i < data.length; i++) {
                if (data[i]["PROVIDERID"] == 'baidu') {
                    var gaodePoint = GPS.bd_decrypt(data[i]["LATITUDE"], data[i]["LONGITUDE"]);
                    data[i]["LATITUDE"] = gaodePoint.lat;
                    data[i]["LONGITUDE"] = gaodePoint.lon;
                } else if (data[i]["PROVIDERID"] == 'gaode') {

                }
                var point = new MapCore.Point([data[i]["LONGITUDE"], data[i]["LATITUDE"]]);
                var marker = new MapCore.Marker(point);
                var obj = data[i];
                /*var imgs = "";
                 $.each(obj,function(key,value){
                 for(var i = 0; i < ThisfieldName.length; i++){
                 if(ThisfieldName[i]["modelattribute"] == key){
                 imgs += "<h>"+ThisfieldName[i]["modelattributename"]+"：" + obj[key] + "</h></br>";
                 console.info(imgs);
                 continue;
                 }
                 }
                 });

                 var files = "";
                 marker.setInfoWindow(imgs);
                 */
                marker.addEvent("click", function (e) {
                    if (fn) {
                        e.point = e.target.getPosition();
                        fn(e);
                    }
                });
                markers.push(marker);
                points.push(point);
            }
            var MarkerClusterer = this.setCluster(markers);
            if (points.length < 2000) {
                //点少时自动调整视野
                this.setViewport(points);
                //this.map.setFitView(markers);
            } else {
                this.setCenterAndZoom(centerPoint, 8);
            }
            return MarkerClusterer;
        },
        dataToMassMarks: function (data) {							//海量点
            if (data == undefined && tbName == undefined) {
                alert("参数不可为空！");
                return;
            }
            if (data.length == 0) {
                alert("没有要标注的地址");
                return;
            }
            var points = [];
            for (var i = 0; i < data.length; i++) {
                if (data[i]["PROVIDERID"] == 'baidu') {
                    var gaodePoint = GPS.bd_decrypt(data[i]["LATITUDE"], data[i]["LONGITUDE"]);
                    data[i]["LATITUDE"] = gaodePoint.lat;
                    data[i]["LONGITUDE"] = gaodePoint.lon;
                } else if (data[i]["PROVIDERID"] == 'gaode') {

                }
                //var point = new MapCore.Point([data[i]["LONGITUDE"], data[i]["LATITUDE"]]);
                var point = { lnglat: [data[i]["LONGITUDE"], data[i]["LATITUDE"]], name: data[i], id: i };
                points.push(point);
            }
            var mass = new AMap.MassMarks(points, {
                url: 'gateWayAddress/webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
                anchor: new AMap.Pixel(3, 7),
                size: new AMap.Size(5, 7),
                opacity: 1,
                cursor: 'pointer',
                zIndex: 100
            });
            mass.setMap(this.map);
            return mass;
        },

        /**
         *
         * @param size
         * @param tag
         * @return
         */
        getOffsetOfTag: function (size, tag) {
            tag = tag.toUpperCase();
            var vanchor = new AMap.Pixel(size.width / 2, size.height / 2);
            if (tag == "MAPC_CENTER") {
                vanchor = new AMap.Pixel(size.width / 2, size.height / 2);
            }
            else if (tag == "MAPC_TOP_CENTER") {
                vanchor = new AMap.Pixel(size.width / 2, 0);
            }
            else if (tag == "MAPC_TOP_LEFT") {
                vanchor = new AMap.Pixel(0, 0);
            }
            else if (tag == "MAPC_TOP_RIGHT") {
                vanchor = new AMap.Pixel(size.width, 0);
            }
            else if (tag == "MAPC_BOTTOM_CENTER") {
                vanchor = new AMap.Pixel(size.width / 2, size.height);
            }
            else if (tag == "MAPC_BOTTOM_LEFT") {
                vanchor = new AMap.Pixel(0, size.height);
            }
            else if (tag == "MAPC_BOTTOM_RIGHT") {
                vanchor = new AMap.Pixel(size.width, size.height);
            }
            else if (tag == "MAPC_LEFT_CENTER") {
                vanchor = new AMap.Pixel(0, size.height / 2);
            }
            else if (tag == "MAPC_RIGHT_CENTER") {
                vanchor = new AMap.Pixel(size.width, size.height / 2);
            }
            return vanchor;
        },
        /**
         *
         * @param data
         * @param options
         *    {
					size:	BMAP_POINT_SIZE_SMALL,    	//海量点尺寸
					shape: BMAP_POINT_SHAPE_STAR,		//海量点形状
					color: 'red'						//海量点颜色
			}
         * @param url
         * @return
         */
        dataToMassMarksByOptions: function (data, options, url) {
            if (data == undefined && tbName == undefined) {
                alert("参数不可为空！");
                return;
            }
            if (data.length == 0) {
                alert("没有要标注的地址");
                return;
            }
            var points = [];
            for (var i = 0; i < data.length; i++) {
                if (data[i]["PROVIDERID"] == 'baidu') {
                    var gaodePoint = GPS.bd_decrypt(data[i]["LATITUDE"], data[i]["LONGITUDE"]);
                    data[i]["LATITUDE"] = gaodePoint.lat;
                    data[i]["LONGITUDE"] = gaodePoint.lon;
                } else if (data[i]["PROVIDERID"] == 'gaode') {

                }
                //var point = new MapCore.Point([data[i]["LONGITUDE"], data[i]["LATITUDE"]]);
                var point = { lnglat: [data[i]["LONGITUDE"], data[i]["LATITUDE"]], name: data[i], id: i };
                points.push(point);
            }
            var vsize = new AMap.Size(5, 7);
            var vanchor = new AMap.Pixel(3, 7);
            var vopacity = 1;
            var vcursor = 'pointer';
            var vzindex = 1000;

            //如果配置自定义
            if (options) {
                if (options.size != undefined) {
                    vsize = options.size;
                    if (options.anchor != undefined) {//根据anchor数值直接设置偏移量
                        vanchor = options.anchor;
                    }
                    else {
                        //如果没有tag，默认是中心点
                        vanchor = map.getOffsetOfTag(options.size, options.anchortag);
                    }
                }
                else {
                    //console.log("按照默认图标设置大小(5,7)、偏移(3,7)、透明度(1)");
                }
            } else {
                //console.log("按照默认图标设置大小(5,7)、偏移(3,7)、透明度(1)");
            }


            var mass = new AMap.MassMarks(points, {
                url: url,
                anchor: vanchor,
                size: vsize,
                opacity: vopacity,
                cursor: vcursor,
                zIndex: vzindex
            });
            mass.setMap(this.map);
            return mass;
        },
        dataToMassMarksByEXOptions: function (data, options, url) { //海量点，偏移量
            if (data == undefined && tbName == undefined) {
                alert("参数不可为空！");
                return;
            }
            if (data.length == 0) {
                alert("没有要标注的地址");
                return;
            }
            var points = [];
            for (var i = 0; i < data.length; i++) {
                if (data[i]["PROVIDERID"] == 'baidu') {
                    var gaodePoint = GPS.bd_decrypt(data[i][1], data[i][0]);
                    data[i][1] = gaodePoint.lat;
                    data[i][0] = gaodePoint.lon;
                } else if (data[i]["PROVIDERID"] == 'gaode') {

                }
                //var point = new MapCore.Point([data[i][0], data[i][1]]);

                var point = { lnglat: [data[i][0], data[i][1]], name: data[i], id: i };
                points.push(point);
            }
            var size1 = new AMap.Size(5, 7);
            //if(url.indexOf('flag.png')>=0||url.indexOf('redStar.png')>=0){
            //size1 = new AMap.Size(15,15);
            //}
            //根据百度大小定义
            if (options && options.size == 1/*BMAP_POINT_SIZE_TINY*/) {
                size1 = new AMap.Size(2, 2);
            } else if (options && options.size == 2/*BMAP_POINT_SIZE_SMALLER*/) {
                size1 = new AMap.Size(4, 4);
            } else if (options && options.size == 3/*BMAP_POINT_SIZE_SMALL*/) {
                size1 = new AMap.Size(8, 8);
            } else if (options && options.size == 4/*BMAP_POINT_SIZE_NORMAL*/) {
                size1 = new AMap.Size(10, 10);
            } else if (options && options.size == 5/*BMAP_POINT_SIZE_BIG*/) {
                size1 = new AMap.Size(16, 16);
            } else if (options && options.size == 6/*BMAP_POINT_SIZE_BIGGER*/) {
                size1 = new AMap.Size(20, 20);
            } else {//BMAP_POINT_SIZE_HUGE
                size1 = new AMap.Size(5, 7);
            }
            //设置图片偏移量，anchor为空则默认（3，7）
            var anchor = options.anchor || new AMap.Pixel(3, 7);

            var mass = new AMap.MassMarks(points, {
                url: url,
                anchor: anchor,
                //size:new AMap.Size(10,10),
                size: size1,
                opacity: 1,
                cursor: 'pointer',
                alwaysRender: false,
                zIndex: options && options.zIndex ? options.zIndex : 999
            });
            mass.setMap(this.map);
            var result = [mass, points];
            return result;
        },

        addMassMarker: function (json) {
            if (!json.data) {
                return;
            }
            var options = json.options;
            var points = [];
            var gaodePoints = [];
            var data = json.data;
            for (var i = 0; i < data.length; i++) {

                var lng = data[i]["LONGITUDE"];
                var lat = data[i]["LATITUDE"];
                var providerId = data[i]["PROVIDERID"];
                var id = data[i]["ID"];

                if (data[i] instanceof Array) {

                    var lng = data[i][0];
                    var lat = data[i][1];
                    var providerId = data[i][2];
                }

                if (providerId == 'baidu') {
                    var gaodePoint = GPS.bd_decrypt(data[i][1], data[i][0]);
                    lat = gaodePoint.lat;
                    lng = gaodePoint.lon;
                } else if (providerId == 'gaode') {

                }
                var gpoint = new MapCore.Point([lng, lat]);
                //gpoint.sourceData=data[i];
                gaodePoints.push(gpoint);

                var point = { lnglat: [lng, lat], sourceData: data[i] };
                points.push(point);
            }
            var size1 = new AMap.Size(5, 7);
            //if(url.indexOf('flag.png')>=0||url.indexOf('redStar.png')>=0){
            //size1 = new AMap.Size(15,15);
            //}
            //根据百度大小定义
            if (options && options.size == 1) {
                size1 = new AMap.Size(2, 2);
            } else if (options && options.size == 2) {
                size1 = new AMap.Size(4, 4);
            } else if (options && options.size == 3) {
                size1 = new AMap.Size(8, 8);
            } else if (options && options.size == 4) {
                size1 = new AMap.Size(10, 10);
            } else if (options && options.size == 5) {
                size1 = new AMap.Size(12, 12);
            } else if (options && options.size == 6) {
                size1 = new AMap.Size(14, 14);
            } else if (options && options.size == 7) {
                size1 = new AMap.Size(16, 16);
            } else if (options && options.size == 8) {
                size1 = new AMap.Size(18, 18);
            } else if (options && options.size == 9) {
                size1 = new AMap.Size(20, 20);
            } else {//BMAP_POINT_SIZE_HUGE
                size1 = new AMap.Size(5, 7);
            }

            var mass = new AMap.MassMarks(points, {
                url: options.iconUrl,
                anchor: new AMap.Pixel(3, 7),
                //size:new AMap.Size(10,10),
                size: size1,
                opacity: 1,
                cursor: 'pointer',
                alwaysRender: false,
                zIndex: options && options.zIndex ? options.zIndex : 999
            });
            mass.setMap(this.map);

            if (json.clickFun) {
                mass.on('click', function (e) {
                    e.point = e.data.lnglat;
                    e.point.sourceData = e.data.sourceData;
                    json.clickFun(e);
                });

            }
            var result = [mass, gaodePoints];
            return result;
        },
        massMarksAddInfo: function (data, mass, ThisfieldName) {												//给海量点添加信息窗
            var markers = [];
            var points = [];
            mass.on('click', function (e) {
                var obj = e.data.name;
                var imgs = "";
                $.each(obj, function (key, value) {
                    for (var i = 0; i < ThisfieldName.length; i++) {
                        if (ThisfieldName[i]["modelattribute"] == key) {
                            imgs += "<h>" + ThisfieldName[i]["modelattributename"] + "：" + obj[key] + "</h></br>";
                            continue;
                        }
                    }
                });
                var infoWindow = new AMap.InfoWindow({
                    autoMove: false
                });
                infoWindow.setContent(imgs);
                infoWindow.open(map.map, e.data.lnglat);
            });

        },
        massMarksAddInfoByText: function (mass, callBack) {												//给海量点添加信息窗
            if (mass == undefined) {
                return;
            }
            if (typeof (callBack) != 'function') {
                alert("callBack必须为函数类型");
                return;
            }
            mass.on('click', function (e) {
                e.point = e.data.lnglat;
                callBack(e);
            });

        },
        route: function () {																//添加导航功能
            var p1;
            var p2;
            var menu = new AMap.ContextMenu();
            var contextMenuPositon;
            var beginStr = '';
            var endStr = '';
            //文本框
            var opts = {
                width: 200,
                height: 100
            }

            $("#r-beginEnd").html(beginStr + "<br/>" + endStr + "<br/>");

            var txtMenuItem = [
                {
                    text: '设为起点',
                    callback: function (e) {
                        //alert(e.lng+","+e.lng);
                        p1 = contextMenuPositon;
                    }
                },
                {
                    text: '设为终点',
                    callback: function (e) {
                        //alert(e.lng+","+e.lng);
                        p2 = contextMenuPositon;
                        driving.search(p1, p2);
                    }
                }
            ];

            for (var i = 0; i < txtMenuItem.length; i++) {
                menu.addItem(txtMenuItem[i].text, txtMenuItem[i].callback || function () {
                }, i);
            }
            map.map.on('rightclick', function (e) {
                menu.open(map.map, e.lnglat);
                contextMenuPositon = e.lnglat;
            });

            var driving = new AMap.Driving({
                map: map.map
            });
        },
        //---------------add by ltq  20151117  end----------------//
        //---------------add by zbs  20151117  start----------------//
        /**
         * 添加覆盖物
         * @param data
         */
        addOverlay: function (data) {
            //添加覆盖物
            this.map.add(data);
        },
        /**
         * 移除覆盖物
         */
        clearOverlays: function () {
            //移除覆盖物
            this.map.clearMap();
            this.removeAllClusterers();
            this.removeHeatMap();
            this.removeAllTracks();
        },
        /**
         * 调整视野
         * @param pointArray
         */
        setViewport: function (pointArray, isFast) {						//调整视野
            //console.time('调整视野');
            var markers = [];
            //调整视野
            if (pointArray != null && pointArray != undefined) {
                if (isFast) {
                    var vp = [];
                    if (pointArray.length > 1000) {
                        var a = Math.ceil(pointArray.length / 1000);
                        for (var j = 0; j < pointArray.length; j = j + a) {
                            vp.push(pointArray[j]);
                        }
                    } else {
                        vp = pointArray;
                    }
                    for (var i = 0; i < vp.length; i++) {

                        var point = vp[i];
                        var marker = this.setMarker(point);
                        markers.push(marker);
                    }
                    this.map.setFitView(markers);
                } else {
                    for (var i = 0; i < pointArray.length; i++) {

                        var point = pointArray[i];
                        var marker = this.setMarker(point);
                        markers.push(marker);
                    }
                    this.map.setFitView(markers);
                }

            } else {
                this.map.setFitView();
            }
            //console.timeEnd('调整视野');

        },
        /**
         * 添加自定义覆盖物
         */
        ComplexCustomOverlay: function (div) {
            var point = new MapCore.Point([121.5418, 29.80963]);//宁波
            map.setCenterAndZoom(point, 11);
            var marker = new MapCore.Marker(point);
            marker.setContent(div);
            this.map.add(marker);
        },
        //---------------add by zbs  20151117  end----------------//
        //---------------add by wangqianqian  20151117  start----------------//
        getPoint: function (data) {
            var point = new MapCore.Point(data);
            return point;
        },
        setMarker: function (point) {                                                      //添加标志
            var marker = new AMap.Marker({ position: point });
            return marker;
        },
        setPointByProvider: function (point, provider) {                                   //依据地图服务商和点添加标志
            if (provider == 'baidu') {
                var gaodePoint = GPS.bd_decrypt(point.lat, point.lng);
                point.lat = gaodePoint.lat;
                point.lng = gaodePoint.lon;
            } else if (provider == 'gaode') {

            }
            var newPoint = new MapCore.Point([point.lng, point.lat]);
            return newPoint;
        },
        setMarkerByProvider: function (point, provider) {                                   //依据地图服务商和点添加标志
            if (provider == 'baidu') {
                var gaodePoint = GPS.bd_decrypt(point.lat, point.lng);
                point.lat = gaodePoint.lat;
                point.lng = gaodePoint.lon;
            } else if (provider == 'gaode') {

            }
            var marker = new MapCore.Marker(point);
            return marker;
        },
        addTextInfoWindow: function (String, object) {                                       //添加纯文字的信息窗口
            return new AMap.InfoWindow({
                autoMove: false,
                content: String
            });
        },
        addTextImageInfoWindow: function (jsonObj, object) {                                  //添加图文组合的信息窗口
            var text = jsonObj.text;
            var imgUrl = jsonObj.imgUrl;
            var height = jsonObj.height;
            var width = jsonObj.width;
            var title = jsonObj.title;
            var htmlStr = "<h style='font-size:12px;margin-top:15px;'>" + text + "</h><br/>" +
                "<img alt='' src='" + imgUrl + "' style='width:" +
                width + "px;height:" + height + "px;'>";
            var infoWindow = new AMap.InfoWindow({
                autoMove: false,
                content: htmlStr
            });
            return infoWindow;
        },
        addMultipointInfo: function (data_info, opts) { //为多个点增加信息窗
            var infoWindowArr = new Array();
            for (var i = 0; i < data_info.length; i++) {
                var point = data_info[i][0];
                var text = data_info[i][1];
                var marker = new MapCore.Marker(point);
                this.addMarker(marker);
                marker.setInfoWindow(text);
                //				var infoWindow = new AMap.InfoWindow({
                //					autoMove:false,
                //					content:text
                //				});
                //	infoWindowArr[i] = {"point":point,"marker":marker,"infoWindow":infoWindow};
            }
            //	return infoWindowArr;
        },
        openInfoWindow: function (infoWindow, point) {                                      //打开信息窗口
            infoWindow.open(this.map, new AMap.LngLat(point.lng, point.lat));
        },
        //---------------add by wangqianqian  20151117  ------------//
        /**
         * 清除路网
         * @return
         */
        clearRoad: function () {
            var features = [];
            features.push("bg");
            features.push("point");
            features.push("building");
            this.map.setFeatures(features);
        },
        getBounds: function () { //返回地图的可视区域，以地理坐标标示
            return this.map.getBounds();
        },
        getLocation: function (point, callback) {  //逆地址解析
            var MGeocoder;
            AMap.service(["AMap.Geocoder"], function () {
                MGeocoder = new AMap.Geocoder({
                    radius: 1000,
                    extensions: "all"
                });
                MGeocoder.getAddress(point, function (status, result) {
                    if (status == 'complete' && result.info == 'OK') {
                        var addComp = result.regeocode.addressComponent;
                        callback(addComp);
                    }
                });
            });
        },
        getCopyrightControl: function () {
            return null;
        },
        getNavigationControl: function () {
            var toolBar;
            var myMap = this.map;
            myMap.plugin(["AMap.ToolBar"], function () {
                toolBar = new AMap.ToolBar();
            });
            return toolBar;
        },
        addCopyright: function (control, id, legendText, bs) {
            AMap.HomeControl1 = function () {
            };
            AMap.HomeControl1.prototype = {
                constructor: AMap.HomeControl1,
                addTo: function (map, dom) {
                    dom.appendChild(this._getHtmlDom(map));
                },
                _getHtmlDom: function (map) {
                    this.map = map;
                    //创建div元素
                    var controlUI = this.container = document.createElement("div");
                    controlUI.innerHTML = legendText;
                    return controlUI;
                }
            }
            var homeControl1 = new AMap.HomeControl1(map);
            this.map.addControl(homeControl1);
        },
        removeCopyright: function (control, id) {
            control.removeCopyright(id);
        },
        /**
         * 画多边形
         */
        drawPolygon2: function (json, isEdit, initCall) {
            var meMap = this;
            if (!json) {
                alert('参数不能为空');
                return;
            }
            var points = json.points;
            if (!points || points.length == 0) {
                alert('坐标点不能为空');
                return;
            }
            var polygons = new Array();
            for (var i = 0; i < points.length; i++) {
                var lon = points[i].lon;//经度
                var lat = points[i].lat;//纬度
                if (!lon || !lat) {
                    alert('数据有误，存在经纬度为空[' + lon + "," + lat + ']');
                    return;
                }
                polygons.push([lon, lat]);
            }

            var polygon = new AMap.Polygon({
                map: this.map,
                strokeWeight: json.strokeWeight ? json.strokeWeight : 2,
                path: polygons,
                fillOpacity: json.fillOpacity ? json.fillOpacity : 0.1,
                fillColor: json.fillColor ? json.fillColor : '#FFF',
                strokeColor: json.strokeColor ? json.strokeColor : '#ff0000'
            });
            if (isEdit) {
                meMap.overlays.push(polygon);
            }


            var paths = polygon.getPath();
            // console.log(paths);
            if (initCall) {
                initCall.initFun(paths);
            }

            var strpoint = "";
            for (var i = 0; i < paths.length; i++) {//循环打印所有标志性坐标
                if (i > 0) {
                    strpoint += ",";
                }
                strpoint += (paths[i].lng + "," + paths[i].lat);
            }
            json = { "type": "polygon", "point": strpoint, "provider": "gaode" };
            if (isEdit) {
                meMap.resultJson.push(json);
                console.log(meMap.resultJson);

                meMap.map.plugin(['AMap.PolyEditor'], function () {
                    var polyEditor = new AMap.PolyEditor(meMap.map, polygon);
                    addEdit("polygon", polyEditor, polygon);
                });
                // 添加图形编辑菜单
                function addEdit(type, polyEditor, plane) {
                    var menu = new AMap.ContextMenu();
                    var txtMenuItem = [
                        {
                            text: '编辑',
                            callback: function () {
                                // console.log(plane);
                                polyEditor.open();
                            }
                        },
                        {
                            text: '关闭',
                            callback: function () {
                                // console.log(plane);
                                polyEditor.close();
                                var paths = plane.getPath();
                                // console.log(paths);
                                if (initCall) {
                                    initCall.initFun(paths);
                                }
                                var strpoint = "";
                                for (var i = 0; i < paths.length; i++) {//循环打印所有标志性坐标
                                    if (i > 0) {
                                        strpoint += ",";
                                    }
                                    strpoint += (paths[i].lng + "," + paths[i].lat);
                                }
                                json = { "type": "polygon", "point": strpoint, "provider": "gaode" };
                                meMap.resultJson.push(json);
                                // console.log(meMap.resultJson);
                            }
                        }
                    ];

                    for (var i = 0; i < txtMenuItem.length; i++) {
                        menu.addItem(txtMenuItem[i].text, txtMenuItem[i].callback || function () {
                        }, i);
                    }
                    plane.on('rightclick', function (e) {
                        menu.open(meMap.map, e.lnglat);
                    });

                }
            }

            this.setMeMapValue('drawPolygon', { points: points });
        },
        drawPolygon: function (json) {
            if (!json) {
                alert('参数不能为空');
                return;
            }
            var points = json.points;
            if (!points || points.length == 0) {
                alert('坐标点不能为空');
                return;
            }
            var polygons = new Array();
            for (var i = 0; i < points.length; i++) {
                var lon = points[i].lon;//经度
                var lat = points[i].lat;//纬度
                if (!lon || !lat) {
                    alert('数据有误，存在经纬度为空[' + lon + "," + lat + ']');
                    return;
                }
                polygons.push([lon, lat]);
            }

            var polygon = new AMap.Polygon({
                map: this.map,
                strokeWeight: json.strokeWeight ? json.strokeWeight : 2,
                path: polygons,
                fillOpacity: json.fillOpacity ? json.fillOpacity : 0.1,
                fillColor: json.fillColor ? json.fillColor : '#FFF',
                strokeColor: json.strokeColor ? json.strokeColor : '#ff0000'
            });
            this.setMeMapValue('drawPolygon', { points: points });
            return polygon;
        },
        /**
         * 画圆
         */
        drawCircle: function (json) {
            if (!json) {
                alert('参数不能为空');
                return;
            }
            json = map.convertJson(json);
            if (!json.lon || !json.lat || !json.radius) {
                alert('数据格式有误');
                return;
            }
            var circle = new AMap.Circle({
                center: new AMap.LngLat(json.lon, json.lat),
                radius: json.radius,
                strokeWeight: json.strokeWeight ? json.strokeWeight : 2,
                fillOpacity: json.fillOpacity ? json.fillOpacity : 0.1,
                fillColor: json.fillColor ? json.fillColor : '#FFF',
                strokeColor: json.strokeColor ? json.strokeColor : '#ff0000'
            });
            circle.setMap(this.map);
            this.setMeMapValue('drawPolygon', { point: json });
        },
        /**
         * 在行政区上添加颜色块覆盖物
         * @param name  行政区域名称
         * @param fillColor 要填充的颜色
         * @param text  提示信息框的文本HTML
         * @param Mapfunction1
         * @param polygonLoadEndfunction  覆盖物执行结束后调用的回调函数
         * @return
         */
        setBound: function (data, Mapfunction1, conditionString, Mapfunction2, fillOpacityNum, isMouseout) {
            AMap.service('AMap.DistrictSearch', function () {
                var opts = {
                    subdistrict: 0,
                    extensions: 'all',
                    level: 'city'
                };
                GdDistrict = new AMap.DistrictSearch(opts);
                GdDistrict.setLevel('city');
                var type = data[0].type;
                for (var j = 0; j < data.length; j++) {
                    var bdname = data[j].area;
                    var gdname = data[j].GDarea;
                    var color = data[j].color;
                    var totalCount = data[j].totalCount;
                    var totalValue = data[j].totalValue;
                    var text = null;
                    if (type == "1" && totalCount != "0") {
                        text = bdname + "</br>" + conditionString + ":" + format(Math.round(totalCount), 3, ',');
                        this.map.search(gdname, color, text, Mapfunction1, Mapfunction2, fillOpacityNum, isMouseout, data.length);
                    } else if (type == "2" && totalValue != "0") {
                        text = bdname + "</br>" + conditionString + ":" + format(Math.round(totalValue), 3, ',');
                        this.map.search(gdname, color, text, Mapfunction1, Mapfunction2, fillOpacityNum, isMouseout, data.length);
                    } else if (type == "3" && totalValue != "0") {
                        text = bdname + "</br>" + conditionString + ":" + (parseFloat(totalValue)).toFixed(2) + "%";
                        this.map.search(gdname, color, text, Mapfunction1, Mapfunction2, fillOpacityNum, isMouseout, data.length);
                    }
                }
            });
        },
        search: function (gdname, color, text, Mapfunction1, Mapfunction2, fillOpacityNum, isMouseout, data) {
            //setBound的内部调用方法，不作为单独的方法使用
            if (!gdname) {
                if (typeof (Mapfunction2) == 'function') {
                    Mapfunction2("", "", "gaode", data);
                }
                return;
            }

            var storage = window.localStorage;
            var bl = false;
            var ssName = "bounds_" + text.substr(0, text.indexOf('<'));
            var bounds = map.getStorageData(ssName);//获得浏览器数据
            if (bounds) {
                //	console.log("使用浏览器数据-------------");
                bl = true;
                map.getSearchData(jQuery.parseJSON(bounds), color, text, Mapfunction1);
                if (typeof (Mapfunction2) == 'function') {
                    Mapfunction2("", "", "gaode", data);
                }
            }
            //查询先查询本地数据库，如果本地没有则在查询高德地图
            if (!bl) {
                var url = map.getRootPath() + '/modelattributes/map/searchDistrict.do';
                $.post(url, { name: ssName }, function (dataResult) {
                    if (!dataResult.result) {
                        try {
                            dataResult = jQuery.parseJSON(dataResult);
                        } catch (e) {
                        }
                    }
                    if (dataResult.result == 'ok') {//查询后台数据库
                        //	console.log("查询后台数据库----------")
                        bl = true;
                        var resultJson = jQuery.parseJSON(map.getStorageDataJson(dataResult.data));
                        map.getSearchData(resultJson, color, text, Mapfunction1);
                        if (typeof (Mapfunction2) == 'function') {
                            Mapfunction2("", "", "gaode", data);
                        }
                        map.saveLoadData(ssName, dataResult.data);

                    } else {//调用高德地图查询
                        //console.log("调用高德地图查询-----------");
                        GdDistrict.search(gdname, function (status, result) {
                            if (status == 'no_data') {
                                if (typeof (Mapfunction2) == 'function') {
                                    Mapfunction2("", "", "gaode", data);
                                }
                            } else {
                                this.map.getSearchData(result, color, text, Mapfunction1);
                                if (typeof (Mapfunction2) == 'function') {
                                    Mapfunction2("", "", "gaode", data);
                                }
                            }
                        });
                    }

                });
            }

        },
        searchBorder: function (gdname, Mapfunction1) {                                             //setBound的内部调用方法，不作为单独的方法使用
            /**
             var ssName = "bounds_"+gdname;
             var bounds = map.getStorageData(ssName);//获得浏览器数据
             if(bounds){
				bl=true;
				map.getSearchBorderData(jQuery.parseJSON(bounds),Mapfunction1);
			}else{
				if(!gdname){
					return;
				}
				GdDistrict.search(gdname,function(status,result){
					//console.info(gdname);
					//console.info(result);
					this.map.getSearchBorderData(result,Mapfunction1);
				});
			}
             **/
            if (!gdname) {
                return;
            }
            var ssName = "border_" + gdname;
            if (typeof (gd_show_text) != 'undefined' && gd_show_text.indexOf('<') >= 0) {
                ssName = "border_" + gd_show_text.substr(0, gd_show_text.indexOf('<'));
            }
            var bounds = map.getStorageData(ssName);//获得浏览器数据
            var bl = false;
            if (bounds && bounds != '') {
                bl = true;
                map.getSearchBorderData(jQuery.parseJSON(bounds), Mapfunction1);
            }
            /**
             GdDistrict.search(gdname,function(status,result){
				//console.info(gdname);
				//console.info(result);
				this.map.getSearchBorderData(result,Mapfunction1);
			});
             **/
            //查询先查询本地数据库，如果本地没有则在查询高德地图
            if (!bl) {
                var url = map.getRootPath() + '/modelattributes/map/searchDistrict.do';
                $.post(url, { name: ssName }, function (dataResult) {
                    if (!dataResult.result) {
                        try {
                            dataResult = jQuery.parseJSON(dataResult);
                        } catch (e) {
                        }
                    }
                    if (dataResult.result == 'ok') {//查询后台数据库
                        bl = true;
                        var resultJson = jQuery.parseJSON(map.getStorageDataJson(dataResult.data));
                        map.getSearchBorderData(resultJson, Mapfunction1);
                        map.saveLoadData(ssName, dataResult.data);

                    } else {//调用高德地图查询
                        GdDistrict.search(gdname, function (status, result) {
                            this.map.getSearchBorderData(result, Mapfunction1);
                            //保持红色边界边框
                            map.saveBorderData(ssName, result);

                        });
                    }
                });
            }

        },
        getSearchData: function (e, color, text, Mapfunction1) {
            //setBound的内部调用方法，不作为单独的方法使用
            var bounds = e;
            if (!e.info) {//使用本地数据或查询系统后台
                var temp = [];
                for (var i = 0; i < bounds.length; i++) {
                    var dianArray = [];
                    for (var j = 0; j < bounds[i].length; j++) {
                        var dian = new AMap.LngLat(bounds[i][j][0], bounds[i][j][1]);
                        dianArray.push(dian);
                    }
                    temp.push(dianArray);
                }
                bounds = temp;

            } else {
                var ssName = "bounds_" + text.substr(0, text.indexOf('<'));
                var sizeNum = map.getDataCXSize(ssName);

                bounds = e.districtList[0].boundaries;
                var temp = [];
                var loadTemp = [];//本地存储
                for (var i = 0; i < bounds.length; i++) {
                    var pst = [];
                    var loadPst = [];
                    for (var j = 0; j < bounds[i].length; j = j + sizeNum) {
                        var obj1 = new Array();
                        obj1.push(bounds[i][j].lng);
                        obj1.push(bounds[i][j].lat);
                        loadPst.push(obj1);//本地存储
                        pst.push(bounds[i][j]);//当前使用
                    }
                    temp.push(pst);
                    loadTemp.push(loadPst);
                }
                bounds = temp;
                var loadTempStr = JSON.stringify(loadTemp);
                //上传到服务器
                map.uploadMapData(ssName, loadTempStr);
                //保持到本地
                map.saveLoadData(ssName, loadTempStr);
            }
            if (bounds) {
                for (var i = 0, l = bounds.length; i < l; i++) {
                    var polygon;
                    if (color.type == 'json') {
                        color.style.path = bounds[i];
                        polygon = new AMap.Polygon(color.style);
                        cityRect = map.getRect(bounds[i], cityRect);
                    } else {
                        polygon = new AMap.Polygon({
                            map: this.map,
                            strokeWeight: 1,
                            path: bounds[i],
                            fillOpacity: 0.5,
                            fillColor: color,
                            strokeColor: '#000',
                            zIndex: 2
                        });
                    }
                    this.polygonAddMouse(text, polygon);
                    this.polygonDbclick(polygon, Mapfunction1, text);
                }
            }

            if (color.type == 'json') {
                if (color.isfinish == 1) {
                    //	console.log( "adjust viewport!!!");
                    map.setViewport([new AMap.LngLat(cityRect.minLng, cityRect.minLat),
                        new AMap.LngLat(cityRect.maxLng, cityRect.maxLat)], false);
                }
            }

        },
        getSearchBorderData: function (e, Mapfunction1) {                                          //setBound的内部调用方法，不作为单独的方法使用
            var bounds = e;
            if (!e.info) {//使用本地数据或查询系统后台
                var temp = [];
                for (var i = 0; i < bounds.length; i++) {
                    var dianArray = [];
                    for (var j = 0; j < bounds[i].length; j++) {
                        var dian = new AMap.LngLat(bounds[i][j][0], bounds[i][j][1]);
                        dianArray.push(dian);
                    }
                    temp.push(dianArray);
                }
                bounds = temp;

            } else {
                bounds = e.districtList[0].boundaries;
            }

            if (bounds) {
                for (var i = 0, l = bounds.length; i < l; i++) {
                    var polygon = new AMap.Polygon({
                        map: this.map,
                        strokeWeight: 2,
                        path: bounds[i],
                        fillOpacity: 0.1,
                        fillColor: '#FFF',
                        strokeColor: '#ff0000',
                        zIndex: 1
                    });
                }
            }
        },
        polygonAddMouse: function (text, polygon) {                                               //setBound的内部调用方法，不作为单独的方法使用
            if (text != null || text != undefined) {
                var infoWindow;
                AMap.event.addListener(polygon, "mousemove", function (e) {
                    ////console.log("移入移出覆盖物坐标:"+e.lnglat.lng+","+e.lnglat.lat);
                    infoWindow = new AMap.InfoWindow({
                        autoMove: false,
                        content: text
                    });  // 创建信息窗口对象
                    infoWindow.open(map.map, e.lnglat); //开启信息窗口
                });
                AMap.event.addListener(polygon, "mouseout", function (e) {
                    ////console.log("移入移出覆盖物坐标:"+e.lnglat.lng+","+e.lnglat.lat);
                    infoWindow.close();
                });
            }
        },
        polygonDbclick: function (polygon, Mapfunction1, text) {                                        //setBound的内部调用方法，不作为单独的方法使用
            AMap.event.addListener(polygon, "dblclick", function (e) {
                //console.log("双击覆盖物坐标:"+e.lnglat.lng+","+e.lnglat.lat);
                epoint = e.lnglat;
                if (text) {
                    epoint.gd_show_text = text;
                }
                Mapfunction1(epoint, true);
            });
        },
        /**
         * 根据地区名划边框
         * @param name 行政区域名称
         * @param tzmap 地图对象
         * @return
         */
        setChineseMapBorder: function (name, Mapfunction1, Mapfunction2) {
            AMap.service('AMap.DistrictSearch', function () {
                var opts = {
                    subdistrict: 1,
                    extensions: 'all',
                    level: 'city'
                };
                GdDistrict = new AMap.DistrictSearch(opts);
                GdDistrict.setLevel('district');
                this.map.searchBorder(name, Mapfunction1);

            });
        },

        /**
         * 在行政区上添加颜色块覆盖物
         * @param name  行政区域名称
         * @param fillColor 要填充的颜色
         * @param text  提示信息框的文本HTML
         * @return
         */
        /** setBound:function(name,gdname, fillColor, text,tzmap,Mapfunction1) {
			////console.log("name:"+gdname);
			////console.log("fillColor:"+fillColor);
			////console.log("text:"+text);
			////console.log("tzmap:"+tzmap);
			var mymap = tzmap.map;
			AMap.service('AMap.DistrictSearch',function(){
				var opts = {
					subdistrict:1,
					extensions:'all',
					level:'city'
				};
				////console.log("进入AMap.DistrictSearch");
				GdDistrict = new AMap.DistrictSearch(opts);
				GdDistrict.setLevel('district');
				GdDistrict.search(gdname,function(status,result){
					////console.log("进入GdDistrict.search");
					var bounds = result.districtList[0].boundaries;
					if(bounds){
						for(var i =0,l=bounds.length;i<l;i++){
							var polygon = new AMap.Polygon({
								strokeWeight:1,
								path:bounds[i],
								fillOpacity:0.7,
								fillColor:fillColor,
								strokeColor:'#fff'
							});
							polygon.setMap(mymap);
							if(text!=null||text!=undefined){
								AMap.event.addListener(polygon,"mouseover",function(e){
									////console.log("移入移出覆盖物坐标:"+e.lnglat.lng+","+e.lnglat.lat);
									var infoWindow = new AMap.InfoWindow({
										autoMove:false,
										content:text
									});  // 创建信息窗口对象
									infoWindow.open(mymap,e.lnglat); //开启信息窗口
								});
							}
							AMap.event.addListener(polygon,"dblclick",function(e){
								////console.log("双击覆盖物坐标:"+e.lnglat.lng+","+e.lnglat.lat);
								epoint = e.lnglat;
								Mapfunction1(epoint, true);
							});


						}
						this.map.map.setFitView();
					}

				});
			});
		},**/
        /**
         * 根据地区名划边框
         * @param name 行政区域名称
         * @param tzmap 地图对象
         * @return
         */
        /**setChineseMapBorder:function(name,tzmap,Mapfunction1,text) {
			var mymap = tzmap.map;
			AMap.service('AMap.DistrictSearch',function(){
				var opts = {
					subdistrict:1,
					extensions:'all',
					level:'city'
				};
				GdDistrict = new AMap.DistrictSearch(opts);
				GdDistrict.setLevel('district');
				GdDistrict.search(name,function(status,result){
					var bounds = result.districtList[0].boundaries;
					if(bounds){
						for(var i =0,l=bounds.length;i<l;i++){
							var polygon = new AMap.Polygon({
								map:mymap,
								strokeWeight:2,
								path:bounds[i],
								fillOpacity:0.1,
								fillColor:'#FFF',
								strokeColor:'#ff0000'
							});**/
        /*
         if(text!=null||text!=undefined){
         AMap.event.addListener(polygon,"click",function(e){
         ////console.log("移入移出覆盖物坐标:"+e.lnglat.lng+","+e.lnglat.lat);
         var infoWindow = new AMap.InfoWindow({
         autoMove:false,
         content:text
         });  // 创建信息窗口对象
         infoWindow.open(mymap,e.lnglat); //开启信息窗口
         });
         }*/
        /**AMap.event.addListener(polygon,"dblclick",function(e){
								////console.log("双击覆盖物坐标:"+e.lnglat.lng+","+e.lnglat.lat);
								epoint = e.lnglat;
								Mapfunction1(epoint, true);
							});
         }
         }


         });
         });
         },**/
        /**
         * 创建菜单控件
         * @param map 要加载菜单的地图对象
         * @param dom 菜单元素HTML
         * @return
         */
        createMenuControl: function (tzmap, paradom, position) {
            AMap.HomeControl = function () {
            };
            AMap.HomeControl.prototype = {
                constructor: AMap.HomeControl,
                addTo: function (tzmap, dom) {
                    dom.appendChild(this._getHtmlDom(tzmap));
                },
                _getHtmlDom: function (tzmap) {
                    this.map = tzmap;
                    //创建div元素
                    var controlUI = this.container = paradom;
                    return controlUI;
                }
            }
            var homeControl = new AMap.HomeControl(tzmap);
            tzmap.addControl(homeControl);
        },
        /**
         * 地图事件，目前仅提供返回Point
         * @param callbackName 事件名
         * @param callback  回调函数
         * @return
         */
        addEventListener: function (callbackName, callback) {
            var a;
            this.map.on(callbackName, function (e) {
            	if(e.lnglat){
            		a = MapCore.Point([e.lnglat.getLng(), e.lnglat.getLat()]);
            	}
                callback(a);
            });
        },
        getBoundryData: function (regionLevel, regionName) {
        	      AMap.plugin("AMap.DistrictSearch", function () {
        	        var district = new AMap.DistrictSearch({
        	          extensions: "all",
                      level:
        	            regionLevel === "1" ? "province" : regionLevel === "2" ? "city" : "district",
        	        });

        	        district.search(regionName, function (status, result) {
        	          const allDistrictBorders = result.districtList[0].boundaries;
        	          if (!allDistrictBorders.length > 0) {
        	            return [];
        	          }
        	          let arr = [];
        	          allDistrictBorders.map((item, index) => {
        	            // 多个多边形区域
        	            const borderList = item;
        	            const polygonPointArray = borderList.map((item) => {
        	              return {
        	                lon: parseFloat(item.lng),
        	                lat: parseFloat(item.lat),
        	              };
        	            });
        	   arr.push(polygonPointArray);
        	 });
        	          return arr;
        	        });
        	      });
        	    },
        /**
         * marker绑定事件
         * @param callbackName 事件名
         * @param callback  回调函数
         * @return
         */
        addListener: function (obj, callbackName, callback) {
            map.on(obj, callbackName, callback);
        },
        /**
         * 添加热力图
         * data 点坐标集合
         * var data = [
         {"lng":116.418267,"lat":39.921984,"count":50},
         {"lng":116.423332,"lat":39.916532,"count":51},
         {"lng":116.419787,"lat":39.930658,"count":15},
         {"lng":116.418455,"lat":39.920921,"count":40},
         {"lng":116.418277,"lat":39.921989,"count":50},
         {"lng":116.423432,"lat":39.916432,"count":51},
         {"lng":116.419587,"lat":39.930558,"count":15},
         {"lng":116.418655,"lat":39.920621,"count":40},
         {"lng":116.418767,"lat":39.921784,"count":50},
         {"lng":116.423832,"lat":39.916832,"count":51},
         {"lng":116.419987,"lat":39.930958,"count":15},
         {"lng":116.418055,"lat":39.920021,"count":40}
         *           ];
         *visible 热力图是否显示，默认true
         *opacity 热力的透明度，分别对应heatmap.js的minOpacity和maxOpacity
         *radius 势力图的每个点的半径大小
         *gradient {JSON}热力图的肩膀、渐变区间，gradient如下所示
         *{
		     .2:'rgb(0,225,255)',
		     .5:'rgb(0,110,255)',
		     .8:'rgb(100,0,255)'

		   }
         其中key表示插值的位置，0～1.
         value 为颜色值。
         *
         */
        addHeatmap: function (data, options, max) {
            var max = max || 100;
            var myMap = this.map;
            var that = this;
            if (!HeatmapLoaded.isHeatmapLoaded) {//判断是否已经加载
                new myMap.plugin(["AMap.Heatmap"], function () {
                    window.HeatmapLoaded.isHeatmapLoaded = true;
                    if (!$.isEmptyObject(that.heatmap)) {
                        alert('只能创建一个热力图');
                    } else {
                        //热力图只能创建一个
                        //初始化heatmap对象
                        that.heatmap = new AMap.Heatmap(myMap, {
                            radius: options.radius,//半径
                            gradient: options.gradient,
                            opacity: [0, 0.8]
                        });
                        //设置数据集
                        that.heatmap.setDataSet({
                            data: data,
                            max: max
                        });
                    }
                });
            } else {
                if (!$.isEmptyObject(that.heatmap)) {
                    alert('只能创建一个热力图');
                } else {
                    //热力图只能创建一个
                    //初始化heatmap对象
                    that.heatmap = new AMap.Heatmap(myMap, {
                        radius: options.radius,//半径
                        gradient: options.gradient,
                        opacity: [0, 0.8]
                    });
                    //设置数据集
                    that.heatmap.setDataSet({
                        data: data,
                        max: max
                    });
                }
            }
        },
        //热力图隐藏
        hideHeatMap: function () {
            if (!$.isEmptyObject(this.heatmap)) {
                this.heatmap.hide();
            }
        },
        //热力图显示
        showHeatMap: function () {
            if (!$.isEmptyObject(this.heatmap)) {
                this.heatmap.show();
            }
        },

        //清除热力图
        removeHeatMap: function () {
            if (!$.isEmptyObject(this.heatmap)) {
                // 清除热力图图层
                $("#_amap_heatmap_div_").remove();
                this.heatmap = {};
            }
        },

        //步行路径规划
        walkingRoute: function (options, callback) {
            var myMap = this.map;
            var that = this;
            if (!WalkingLoaded.isWalkingLoaded) {
                new myMap.plugin(["AMap.Walking"], function () {
                    window.WalkingLoaded.isWalkingLoaded = true;//模块加载改变状态
                    that.walking = new AMap.Walking({
                        map: myMap,
                        panel: options.panel || "",
                        isOutline: options.isOutline || true,
                        outlineColor: options.outlineColor || 'white',
                        hideMarkers: options.hideMarkers || false
                    });
                    if (!!options.origin && !!options.destination) {
                        that.walking.search(options.origin, options.destination, function (status, result) {//实现路径规划
                            (typeof callback == "function") && callback.call(window, status, result);
                        })
                    } else if (!!options.data) {
                        that.walking.search(options.data, function (status, result) {//实现路径规划
                            (typeof callback == "function") && callback.call(window, status, result);
                        })
                    }

                })
            } else {
                that.walking.clear();
                if (!!options.origin && !!options.destination) {
                    that.walking.search(options.origin, options.destination, function (status, result) {//实现路径规划
                        (typeof callback == "function") && callback.call(window, status, result);
                    })
                } else if (!!options.data) {
                    that.walking.search(options.data, function (status, result) {//实现路径规划
                        (typeof callback == "function") && callback.call(window, status, result);
                    })
                }
            }

        },
        //驾车路径规划
        drivingRoute: function (options, callback) {
            var myMap = this.map;
            var that = this;
            if (!DrivingLoaded.isDrivingLoaded) {
                new myMap.plugin(["AMap.Driving"], function () {
                    window.DrivingLoaded.isDrivingLoaded = true;//模块加载改变状态
                    that.driving = new AMap.Driving({
                        map: myMap,
                        panel: options.panel || "",
                        isOutline: options.isOutline || true,
                        outlineColor: options.outlineColor || 'white',
                        hideMarkers: options.hideMarkers || false
                    });
                    if (!!options.origin && !!options.destination) {
                        if (!$.isEmptyObject(options.opts)) {//途径点不为空
                            that.driving.search(options.origin, options.destination, { waypoints: options.opts }, function (status, result) {//实现路径规划
                                (typeof callback == "function") && callback.call(window, status, result);
                            })
                        } else {
                            that.driving.search(options.origin, options.destination, function (status, result) {//实现路径规划
                                (typeof callback == "function") && callback.call(window, status, result);
                            })
                        }
                    } else if (!!options.data) {
                        that.driving.search(options.data, function (status, result) {//实现路径规划
                            (typeof callback == "function") && callback.call(window, status, result);
                        })
                    }
                })
            } else {
                that.driving.clear();//清除上一个搜索结果
                if (!!options.origin && !!options.destination) {
                    if (!$.isEmptyObject(options.opts)) {//途径点不为空
                        that.driving.search(options.origin, options.destination, { waypoints: options.opts }, function (status, result) {//实现路径规划
                            (typeof callback == "function") && callback.call(window, status, result);
                        })
                    } else {
                        that.driving.search(options.origin, options.destination, function (status, result) {//实现路径规划
                            (typeof callback == "function") && callback.call(window, status, result);
                        })
                    }
                } else if (!!options.data) {
                    that.driving.search(options.data, function (status, result) {//实现路径规划
                        (typeof callback == "function") && callback.call(window, status, result);
                    })
                }
            }

        },
        //多条驾车路径规划
        drivingMoreRoute: function (options, callback) {
            var myMap = this.map;
            new myMap.plugin(["AMap.Driving"], function () {
                window.DrivingLoaded.isDrivingLoaded = true;//模块加载改变状态
                var drivingMore = new AMap.Driving({
                    map: myMap,
                    panel: options.panel || "",
                    isOutline: options.isOutline || true,
                    outlineColor: options.outlineColor || 'white',
                    hideMarkers: options.hideMarkers || false
                });
                //drivingMore.setPolicy(AMap.DrivingPolicy.LEAST_DISTANCE);
                if (!!options.origin && !!options.destination) {
                    if (!$.isEmptyObject(options.opts)) {//途径点不为空
                        drivingMore.search(options.origin, options.destination, { waypoints: options.opts }, function (status, result) {//实现路径规划
                            (typeof callback == "function") && callback.call(window, status, result);
                        })
                    } else {
                        drivingMore.search(options.origin, options.destination, function (status, result) {//实现路径规划
                            (typeof callback == "function") && callback.call(window, status, result);
                        })
                    }
                } else if (!!options.data) {
                    drivingMore.search(options.data, function (status, result) {//实现路径规划
                        (typeof callback == "function") && callback.call(window, status, result);
                    })
                }
            })

        },
        //公交路径规划
        transferRoute: function (options, city, callback) {
            var myMap = this.map;
            var that = this;
            if (!TransferLoaded.isTransferLoaded) {
                new myMap.plugin(["AMap.Transfer"], function () {
                    window.TransferLoaded.isTransferLoaded = true;//模块加载改变状态
                    that.transfer = new AMap.Transfer({
                        map: myMap,
                        panel: options.panel || "",
                        policy: AMap.TransferPolicy.LEAST_TIME,
                        city: city,
                        isOutline: options.isOutline || true,
                        outlineColor: options.outlineColor || 'white',
                        hideMarkers: options.hideMarkers || false
                    });
                    if (!!options.origin && !!options.destination) {
                        that.transfer.search(options.origin, options.destination, function (status, result) {//实现路径规划
                            (typeof callback == "function") && callback.call(window, status, result);
                        })
                    } else if (!!options.data) {
                        that.transfer.search(options.data, function (status, result) {//实现路径规划
                            (typeof callback == "function") && callback.call(window, status, result);
                        })
                    }
                })
            } else {
                that.transfer.clear();//清除上一个搜索结果
                if (!!options.origin && !!options.destination) {
                    that.transfer.search(options.origin, options.destination, function (status, result) {//实现路径规划
                        (typeof callback == "function") && callback.call(window, status, result);
                    })
                } else if (!!options.data) {
                    that.transfer.search(options.data, function (status, result) {//实现路径规划
                        (typeof callback == "function") && callback.call(window, status, result);
                    })
                }
            }
        },
        /**
         * 坐标转换为高德
         *
         * @param options
         */
        transformXY: function (options, callback) {
            var points = options.points;
            var type = options.type || "baidu";
            AMap.convertFrom(points, type, callback);
        },
        /**
         * 毛毛虫规划：指点起点终点，在指定区域范围内查找点和规划路径
         * @author k4321 20190314
         */
        findBestRoute: function (json) {
            var url = "optimoveAppAddress/optimove/caterpillar/findBestRoute.do";
            json.crossType = true;
            this.runJsonp(json, url, function (data) {
                console.log(data)
            });
        },
        /**
         * 路径规划
         */
        pathPlanning: function (json) {
            json.jsonParams.provider = "10002";//gaode provider
            var url = "optimoveAppAddress/optimove/modelattributes/pathPlanning.do";
            this.runJsonp(json, url);
        },
        /**
         * 距离测量
         */
        getDistanceTool: function (rulerOptions) {
            var myMap = this.map;
            var that = this;
            if (!RangingToolLoaded.isRangingToolLoaded) {//是否已经加载RangingToo类
                myMap.plugin(["AMap.RangingTool"], function () {
                    window.RangingToolLoaded.isRangingToolLoaded = true;
                    if (rulerOptions == null || rulerOptions == undefined) {
                        that.ruler = new AMap.RangingTool(myMap);
                    } else {
                        that.ruler = new AMap.RangingTool(myMap, rulerOptions);
                    }
                    if (that.ruler != undefined) {
                        //开启鼠标测距
                        that.ruler.turnOn();
                        //设置鼠标样式默认为十字
                        myMap.setDefaultCursor("crosshair");
                    }
                    AMap.event.addListener(that.ruler, "end", function (e) {
                        that.ruler.turnOff();
                        myMap.setDefaultCursor(); //还原鼠标样式
                    });
                });
            } else {
                if (that.ruler != undefined) {
                    //开启鼠标测距
                    that.ruler.turnOn();
                    //设置鼠标样式默认为十字
                    myMap.setDefaultCursor("crosshair");
                }
            }
            return that.ruler;
        },
        /**
         * 添加地图绘制工具
         * @param inputId 检索框id
         */
        addDrawingCircleTool: function (inputId) {
            var myMap = this.map;
            var menu = new AMap.ContextMenu();
            var mouseTool;
            var getCircle;
            var CircleObj = "";
            var txtMenuItem = [
                {
                    text: '清除',
                    callback: function (e) {
                        //清空检索框id值
                        if (inputId != "") {
                            $("#" + inputId).val("");
                        }
                        //清除覆盖物
                        //map.clearOverlays();
                        //关闭画圆工具
                        mouseTool.close();
                    }
                }
            ];
            for (var i = 0; i < txtMenuItem.length; i++) {
                menu.addItem(txtMenuItem[i].text, txtMenuItem[i].callback || function () {
                }, i);
            }
            myMap.plugin(['AMap.MouseTool'], function () {
                mouseTool = new AMap.MouseTool(myMap);

                //单击鼠标触发画圆事件
                map.addEventListener('click', function () {
                    //是鼠标工具在地图上画点
                    mouseTool.circle();
                });
                //右击鼠标事件
                map.map.on('rightclick', function (e) {
                    menu.open(map.map, e.lnglat);
                });
                AMap.event.addListener(mouseTool, 'draw', function (e) {
                    ////console.log("type:"+e.type);
                    ////console.log("obj:"+e.obj);
                    getCircle = e.obj;
                    //得到圆的中心点坐标(维度)
                    CircleObj = "lat=" + getCircle.getCenter().lat + "&";
                    //得到圆的中心点坐标(经度)
                    CircleObj += "lng=" + getCircle.getCenter().lng + "&";
                    //圆半径
                    CircleObj += "radius=" + getCircle.getRadius() + "&";
                    //地图服务商名
                    CircleObj += "provider=gaode";
                    if (inputId != "") {
                        var input = $("#" + inputId);
                        input.val(CircleObj);
                        ////console.log("inputValue:"+input.val());
                    }
                }, false);
            });
        },
        /**
         * overlay 覆盖物
         * 删除指定覆盖物
         * @param overlay
         */
        removeAppiontOverlay: function (overlay) {
            if (overlay != undefined) {
                overlay.setMap(null);
            }
        },
        addDrawingCircle: function (inputId) {
            var myMap = this.map;
            var mouseTool;
            //定义点击画圆监听事件遍历变量
            var clickCircle;
            var getCircle;
            //添加鼠标画图工具
            var menu = new AMap.ContextMenu();
            var txtMenuItem = [
                {
                    text: '清除',
                    callback: function (e) {
                        //清空检索框id值
                        if (inputId != "") {
                            $("#" + inputId).val("");
                        }
                        //清除覆盖物
                        //getCircle.setMap(null);
                        map.removeAppiontOverlay(getCircle);
                        //关闭画圆工具
                        mouseTool.close();
                    }
                }
            ];
            for (var i = 0; i < txtMenuItem.length; i++) {
                menu.addItem(txtMenuItem[i].text, txtMenuItem[i].callback || function () {
                }, i);
            }
            //创建一个div容器
            var controlDiv = document.createElement("div");
            controlDiv.style.cursor = "pointer";
            controlDiv.className = 'button-group';
            controlDiv.style.position = 'absolute';
            controlDiv.style.left = '5px';
            controlDiv.style.top = '5px';
            controlDiv.style.height = '1px';
            controlDiv.style.width = '90px';
            //右击鼠标事件
            map.map.on('rightclick', function (e) {
                menu.open(map.map, e.lnglat);
            });
            myMap.plugin(['AMap.MouseTool'], function () {
                mouseTool = new AMap.MouseTool(myMap);
                //画圆button
                var inputCircle = document.createElement("input");
                //设置input 属性
                inputCircle.setAttribute("type", "button");
                inputCircle.setAttribute("value", "画圆");
                inputCircle.setAttribute("class", "button");
                //inputCircle.setAttribute("id", "point");
                inputCircle.onclick = function (e) {
                    //map.addDrawingCircleTool(inputId);
                    //var getCircle;
                    var CircleObj = "";

                    //单击鼠标触发画圆事件
                    //map.map.on('click',function(e){
                    //是鼠标工具在地图上画点
                    mouseTool.circle();
                    //});
                    //第一个圆
                    var oldObj;
                    //鼠标工具完成画圆之后触发事件
                    AMap.event.addListener(mouseTool, 'draw', function (e) {
                        //判断第一个圆是否未定义，如果定义则清除第一个圆
                        if (oldObj != undefined) {
                            //清除指定圆覆盖物
                            //oldObj.setMap(null);
                            map.removeAppiontOverlay(oldObj);
                        }
                        //定义第一个圆
                        oldObj = e.obj;
                        getCircle = e.obj;
                        //得到圆的中心点坐标(维度)
                        CircleObj = "lat=" + getCircle.getCenter().lat + "&";
                        //得到圆的中心点坐标(经度)
                        CircleObj += "lng=" + getCircle.getCenter().lng + "&";
                        //圆半径
                        CircleObj += "radius=" + getCircle.getRadius() + "&";
                        //地图服务商名
                        CircleObj += "provider=gaode";
                        if (inputId != "") {
                            var input = $("#" + inputId);
                            input.val(CircleObj);
                        }
                        //关闭画圆工具
                        mouseTool.close();
                    }, false);

                };
                //画圆按钮添加到div
                controlDiv.appendChild(inputCircle);
                //关闭button
                var inputClose = document.createElement("input");
                //设置input 属性
                inputClose.setAttribute("type", "button");
                inputClose.setAttribute("value", "关闭");
                inputClose.setAttribute("class", "button");
                //inputClose.setAttribute("id", "closeButton");
                inputClose.onclick = function (e) {

                    //清空检索框id值
                    if (inputId != "") {
                        $("#" + inputId).val("");
                    }
                    //清除覆盖物
                    getCircle.setMap(null);
                    //关闭画圆工具
                    mouseTool.close();
                    //删除点击画圆监听事件
                    //map.removeEventListener(clickCircle);
                };
                //画多边形按钮添加到div
                controlDiv.appendChild(inputClose);

                //创建菜单
                map.createMenuControl(map, controlDiv, "");
            });
        },
        addDrawingManager_TEST: function () {
            var myMap = this.map;
            var mouseTool;
            myMap.plugin(['AMap.MouseTool'], function () {
                mouseTool = new AMap.MouseTool(myMap);
            });
            var controlDiv = document.createElement("div");
            controlDiv.style.cursor = "pointer";
            controlDiv.className = 'button-group';
            controlDiv.position = 'absolute';
            controlDiv.style.left = '10px';
            controlDiv.style.top = '10px';
            //画点button
            var inputMarker = document.createElement("input");
            //设置input 属性
            inputMarker.setAttribute("type", "button");
            inputMarker.setAttribute("value", "画点");
            inputMarker.setAttribute("class", "button");
            //inputMarker.setAttribute("id", "marker");
            inputMarker.onclick = function (e) {
                AMap.event.addDomListener(document.getElementById('marker'), 'click',
                    function () {
                        mouseTool.marker();
                    }, false);
                /*map.addEventListener('click',function(){
                 //是鼠标工具在地图上画点
                 mouseTool.marker();
                 });*/
            };
            //画点按钮添加到div
            //controlDiv.appendChild(inputMarker);

            //画圆button
            var inputCircle = document.createElement("input");
            //设置input 属性
            inputCircle.setAttribute("type", "button");
            inputCircle.setAttribute("value", "画圆");
            inputCircle.setAttribute("class", "button");
            //inputCircle.setAttribute("id", "point");
            inputCircle.onclick = function (e) {
                map.addEventListener('click', function () {
                    //是鼠标工具在地图上画点
                    mouseTool.circle();
                });
            };
            //画圆按钮添加到div
            controlDiv.appendChild(inputCircle);

            //画线button
            var inputLine = document.createElement("input");
            //设置input 属性
            inputLine.setAttribute("type", "button");
            inputLine.setAttribute("value", "画线");
            inputLine.setAttribute("class", "button");
            //inputLine.setAttribute("id", "line");
            inputLine.onclick = function (e) {
                map.addEventListener('click', function () {
                    //是鼠标工具在地图上画线
                    mouseTool.polyline();
                });
            };
            //画线按钮添加到div
            //controlDiv.appendChild(inputLine);

            //画多边形button
            var inputPolygon = document.createElement("input");
            //设置input 属性
            inputPolygon.setAttribute("type", "button");
            inputPolygon.setAttribute("value", "画多边形");
            inputPolygon.setAttribute("class", "button");
            //inputPolygon.setAttribute("id", "polygon");
            inputPolygon.onclick = function (e) {
                map.addEventListener('click', function () {
                    //是鼠标工具在地图上画多边形
                    mouseTool.polygon();
                });
            };
            //画多边形按钮添加到div
            //controlDiv.appendChild(inputPolygon);

            //画矩形utton
            var inputRectangle = document.createElement("input");
            //设置input 属性
            inputRectangle.setAttribute("type", "button");
            inputRectangle.setAttribute("value", "画矩形");
            inputRectangle.setAttribute("class", "button");
            //inputRectangle.setAttribute("id", "rectangle");
            inputRectangle.onclick = function (e) {
                map.addEventListener('click', function () {
                    //是鼠标工具在地图上画多边形
                    mouseTool.rectangle();
                });
            };
            //画矩形按钮添加到div
            //controlDiv.appendChild(inputRectangle);

            //关闭button
            var inputClose = document.createElement("input");
            //设置input 属性
            inputClose.setAttribute("type", "button");
            inputClose.setAttribute("value", "关闭");
            inputClose.setAttribute("class", "button");
            //inputClose.setAttribute("id", "closeButton");
            inputClose.onclick = function (e) {
                map.addEventListener('click', function () {
                    //是鼠标工具在地图上画多边形
                    mouseTool.close();
                });
            };
            //画多边形按钮添加到div
            controlDiv.appendChild(inputClose);

            //创建菜单
            map.createMenuControl(map, controlDiv, "");
        },

        /**
         * 输入框联想
         * @param autoOptions
         */
        autoComplete: function (autoOptions) {
            var that = this;

            function select(e) {
                if (!$.isEmptyObject(that._placeSearch)) { //地图有poi工具加入才检索
                    that._placeSearch.search(e.poi.name, function (status, result) {
                    });
                }
            }

            var auto;
            if (!window.AutocompleteLoaded.isAutocompleteLoaded) {	//未加载AMap.Autocomplet,需要加载模块
                AMap.plugin(["AMap.Autocomplete"], function () {
                    window.AutocompleteLoaded.isAutocompleteLoaded = true;
                    auto = new AMap.Autocomplete(autoOptions);        //创建关键字联想
                    AMap.event.addListener(auto, "select", select);   //注册监听，当选择某条记录时触发
                    return auto;
                });

            } else {
                auto = new AMap.Autocomplete(autoOptions);        //创建关键字联想
                AMap.event.addListener(auto, "select", select);   //注册监听，当选择某条记录时触发
                return auto;
            }
        },
        /**
         * POI搜索
         * @param callback 回调函数
         * @param autoOptions 回调函数参数
         * @return
         */
        placeSearch: function (callback, autoOptions) {
            var that = this;
            if (!window.PlaceSearchLoaded.isPlaceSearchLoaded) {	//未加载AMap.PlaceSearch,需要加载模块
                AMap.service(["AMap.PlaceSearch"], function () {
                    window.PlaceSearchLoaded.isPlaceSearchLoaded = true;
                    if ($.isEmptyObject(that._placeSearch)) {
                        that._placeSearch = new AMap.PlaceSearch({
                            map: that.map
                        });
                    }
                    if (typeof callback == "function") {
                        callback.call(that, autoOptions);
                    }
                    return that._placeSearch;
                });
            } else if ($.isEmptyObject(that._placeSearch)) {	//已加载PlaceSearch模块
                that._placeSearch = new AMap.PlaceSearch({
                    map: that.map
                });
                if (typeof callback == "function") {
                    callback.call(that, autoOptions);
                }
                return that._placeSearch;
            }
        },

        /**
         * geoserver添加图层
         * @param json 参数
         * @return
         */
        geoLayers: function (json) {
            var that = this;
            if (!json.layers) {
                alert("layers图层名称不能为空！");
                return;
            }
            var zooms = json.zooms || [10, 22]
            var layers = json.layers;
            var ratio = json.ratio || 1
            var wms = new AMap.TileLayer.WMS({
                url: _geoserverUrl,
                blend: false,
                tileSize: 512,
                zooms: zooms,//可见级别
                params: {
                    'LAYERS': layers, 'VERSION': '1.1.0', 'TILED': false,
                    singleTile: true,
                    ratio: ratio,
                    isBaseLayer: false
                }
                //params: {'LAYERS': 'test:points','TILED': true,'STYLES': 'heatmap'},
            })
            wms.setMap(that.map)
        },

        getProvider: function () {//返回地图服务商
            return "gaode";
        },
        /**
         * 添加右键菜单
         * @param txtMenuItem 右键菜单子项对象数组，
         *                      形式如[{text:'String',callback：function(e)},{text:'String',callback：function(e)},......]
         *                      text为：子项菜单名String类型
         *                      callback为：点击该子项菜单时触发的回调函数，返回值为point坐标点（仅百度的有返回值）。
         * @return    地图服务商名
         */
        addRightMenu: function (txtMenuItem, menuMapObj) {
            //创建地图右键菜单对象
            var menu = new AMap.ContextMenu();
            //循环遍历右键菜单子项，并将子项添加到右键菜单对象中。
            for (var i = 0; i < txtMenuItem.length; i++) {
                menu.addItem(txtMenuItem[i].text, txtMenuItem[i].callback || function () {
                }, i);
            }
            var thisPolygon = map.map.getAllOverlays(menuMapObj);
            for (var i = 0; i < thisPolygon.length; i++) {
                //将右键菜单加入地图中
                thisPolygon[i].on("rightclick", function (e) {
                    menu.open(map.map, e.lnglat);
                });
            }

        },
        setViewportByArea: function (Area) {

        },
        setMassMarksStyles: function (MassMarks, styles) {
        },

        /**
         * 在地图中设置折线
         * @param pointArray 折线经过的点对象数组
         * @param lineOptions 折线初始化的可选参数，形式如{strokeColor:'blue',strokeOpacity:0.5,strokeWeight:2}
         * @return
         */
        setPolyline: function (pointArray, lineOptions) {
            //创建折线
            var polyline = new AMap.Polyline({
                path: pointArray,
                strokeColor: lineOptions.strokeColor,
                strokeOpacity: lineOptions.strokeOpacity,
                strokeWeight: lineOptions.strokeWeight
            });
            return polyline;
        },
        /**
         * 在地图中设置圆
         * @param center 圆心点 point对象类型
         * @param radius 半径 num类型 单位米
         * @param circleOptions 圆的初始化的可选参数，形式如
         * {	strokeColor:'blue',  //圆边线颜色
		 * 		strokeOpacity:0.5,	//圆边线透明度，取值范围0-1
		 * 		fillColor:'blue',  //填充颜色
		 * 		fillOpacity:0.5,	//圆填充颜色明度，取值范围0-1
		 * 		strokeWeight:2,		//边线宽度，以像素为单位
		 * 		enableMassClear:false	//是否能被map.clearOverlays清除，默认true
		 * 		}
         * @return
         */
        setCircle: function (center, radius, circleOptions) {
            circleOptions.center = center;
            circleOptions.radius = radius;
            var circle = new AMap.Circle(circleOptions);
            return circle;
        },
        /*路书*/
        /**
         * 路书，使某图形沿着某点数组移动到功能
         * @param
         * @param opts 路书的初始化可选参数
         * {
		 *		landmarkPois:"",	//要在覆盖物移动过程中显示的特殊点。格式如[{lng:111,lat:39,html:'加油站',payseTime:3}]
		 *		icon:"",			//覆盖物的icon
		 *		speed:"",			//覆盖物移动速度，单位米/秒
		 *		defaultContent:"",	//覆盖物中的内容
		 *		autoView:"",		//是否自动调整路线视野，默认不调整
		 *		enableRotation:""	//是否开启marker随路走向旋转，默认false
			}
         */
        LuShu: function (array, opts) {
            lushu = new AMap.Marker({
                map: this.map.map,
                position: array[0],
                autoRotation: true,
                offset: new AMap.Pixel(-26, -13)
            });
            return lushu;
        },
        LuShuStart: function (lushu) {
            lushu.moveAlong();
        },
        LuShuPause: function (lushu) {
            lushu.pause();
        },
        LuShuStop: function (lushu) {
            lushu.stop();
        },
        /**
         * 动态点标记
         * @param point
         * @returns {AMap.Marker}
         */

        markerMove: function (point) {
            var marker = new AMap.Marker({
                map: this.map,
                position: point,
                icon: "gateWayAddressnbcbimages/car_03.png",
                offset: new AMap.Pixel(-26, -13),
                autoRotation: true
            })
            return marker;
        },
        /**
         * 设置路径轨迹
         * @param pointArray 点几个
         * @param lineOptions 线设置
         * @param isBegin 是否显示起终点
         * @param isMove 是否显示移动标记
         * @returns {AMap.Polyline}
         */
        setTrack: function (pointArray, lineOptions, isBegin, isMove) {
            for (var i = 0; i < pointArray.length; i++) {
                var marker = new MapCore.Marker(pointArray[i]);
                if (isBegin) {
                    //设置开始和结束的图标
                    if (i == 0) {
                        map.setMarkerIcon(marker, "gateWayAddressnbcbimages/startMarker.png");
                    } else if (i == pointArray.length - 1) {
                        map.setMarkerIcon(marker, "gateWayAddressnbcbimages/endMarker.png");
                    } else {
                        map.setMarkerIcon(marker, "gateWayAddressnbcbimages/middleMarker.png");
                    }
                }
                map.addMarker(marker);
            }

            //创建折线
            var polyline = map.setPolyline(pointArray, lineOptions);
            polyline.setMap(this.map);

            //自适应地图
            map.setViewport(pointArray);

            if (isMove) {
                //显示动态点标记
                var stratMove = map.markerMove(pointArray[0]);
                stratMove.moveAlong(pointArray, 5000);
            }
            return polyline;
        },
        /**
         * 地图加载完成事件
         * @param callBack
         * @return
         */
        tilesloaded: function (callBack) {
            if (typeof callBack == 'function') {
                this.map.map.on("complete", callBack);
            }
        },
        //===============================以下待定=======================================
        /**
         * 根据城市名设置地图中心点
         * @param cityName 城市名
         * @param zoom 地图显示级别
         */
        setCenterByCity: function (cityName, zoom) {
            if ((typeof cityName == 'string') && (typeof zoom == 'number')) {
                this.map.setZoom(zoom);
                this.map.setCity(cityName);
            } else {
                alert("所传参数类型错误或者参数值为空");
            }
        },
        /**
         * 添加城市列表控件
         * @return
         */
        setCityListControl: function () {

        },
        /**
         * 创建地面叠加层
         * @param swPoint
         * @param nePoint
         * @param Options
         * @return
         */
        groundOverlay: function (swPoint, nePoint, imgUrl, Options) {
            var GOlay = new AMap.GroundImage(imgUrl, new AMap.Bounds(swPoint, nePoint), Options);
            return GOlay;
        },
        /**
         * 根据ip获取城市名。
         */
        getLocationByIP: function (onSuccess) {
            //实例化城市查询类
            var citysearch = new AMap.CitySearch();
            var map = this.map;
            //自动获取用户IP，返回当前城市
            citysearch.getLocalCity(function (status, result) {
                if (status === 'complete' && result.info === 'OK') {
                    if (result && result.city && result.bounds) {
                        var cityinfo = result.city;
                        var citybounds = result.bounds;
                        if (onSuccess) {
                            onSuccess(result);
                        }
                        //地图显示当前城市
                        map.setBounds(citybounds);
                    }
                } else {
                    alert(result.info);
                }
            });
        },
        /**
         * 根据浏览器获取当前位置
         */
        Geolocation: function (onSuccess) {
            this.map.plugin('AMap.Geolocation', function () {
                geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true,//是否使用高精度定位，默认:true
                    timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                    buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                    zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                    buttonPosition: 'RB'
                });
                map.addControl(geolocation);
                geolocation.getCurrentPosition();
                AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
                AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
            });
            //解析定位结果
            function onComplete(data) {
                var result = {
                    "info": "定位成功", "lng": data.position.getLng(), "lat": data.position.getLat(),
                    "accuracy": data.accuracy, "isConverted": data.isConverted
                };
                if (onSuccess) {
                    onSuccess(result);
                }
            }

            //解析定位错误信息
            function onError(data) {
                if (onSuccess) {
                    onSuccess(null);
                }
                alert("定位失败!");
            }
        },
        /**
         * H5原生定位
         * @param callback 回调函数
         * @param isGeo 定位失败的时候是否使用供应商的浏览器定位服务
         * @return
         */
        getLocationByBrower: function (callback, isGeo) {
            var This = this;
            if (window.navigator.geolocation) {
                var options = {
                    enableHighAccuracy: true, //是否尝试更精确地读取经度和纬度，默认为false
                    timeout: 10000
                };
                window.navigator.geolocation.getCurrentPosition(
                    function (position) {
                        var lng = position.coords.longitude;
                        var lat = position.coords.latitude;
                        var ggpoint = new Array();
                        var pio = new MapCore.Point([lng, lat]);
                        ggpoint.push(pio);
                        AMap.convertFrom(ggpoint, 'gps', function (status, result) {
                            if (status === 'complete' && result.info === 'ok') {
                                lng = result.locations[0].lng;
                                lat = result.locations[0].lat;
                            }
                            var pos = {
                                status: 'ok',
                                lng: lng,
                                lat: lat

                            };
                            callback(pos);
                        });

                    }, function (error) {
                        var pos = {
                            status: 'fail',
                            lng: 0,
                            lat: 0
                        };
                        if (isGeo) {
                            This.Geolocation(callback);
                        } else {
                            callback(pos);
                        }
                    }, options);
            } else {
                alert("浏览器不支持HTML5获取地理位置信息");
            }
        },
        /**
         * 高德坐标转换(gps坐标转高德坐标)
         *@param callback 回调函数
         *@param point 要转换的点
         */
        transCoordinate: function (callback, point) {
            var ggpoint = new Array();
            ggpoint.push(point);
            AMap.convertFrom(ggpoint, 'gps', function (status, result) {
                if (status === 'complete' && result.info === 'ok') {
                    var lng = result.locations[0].lng;
                    var lat = result.locations[0].lat;
                    var po = new MapCore.Point([lng, lat]);
                    var res = {
                        result: 'ok',
                        point: po
                    };
                    callback(res);
                } else {
                    var res = {
                        result: 'fail',
                        point: point
                    };
                    callback(res);
                }
            });
        },
        /**
         * 显示路况信息
         * @para isVisible 是否显示
         */
        TrafficControl: function (isVisible) {
            //实时路况图层
            if (this.trafficLayer == null) {
                this.trafficLayer = new AMap.TileLayer.Traffic({
                    zIndex: 10
                });
                this.trafficLayer.setMap(this.map);
            }
            if (isVisible) {
                this.trafficLayer.show();
            } else {
                this.trafficLayer.hide();
            }
        },
        /**
         * 获取地图显示范围
         */
        getMapBounds: function () {
            var limitBounds = this.map.getLimitBounds();
            if (limitBounds) {
                var tip = [];
                tip.push('限制区域：\n西南坐标[' + limitBounds.southwest.lng + ',' + limitBounds.southwest.lat + ']\n')
                tip.push('东北坐标[' + limitBounds.northeast.lng + ',' + limitBounds.northeast.lat + ']')
                alert(tip.join(''));
            } else {
                alert('未设置限制区域');
            }
        },
        /**
         * 设置地图显示范围
         * @param {Object} pointLeft 左上角的点坐标 地图的Point类型
         * @param {Object} pointRight 右下角的点坐标 地图的point类型
         */
        setMapBounds: function (pointLeft, pointRight) {
            var b = new AMap.Bounds(pointLeft, pointRight);
            this.map.setLimitBounds(b);
        },
        /*
         *清除区域限制
         */
        clearLimitBounds: function () {
            this.map.clearLimitBounds();
        },
        /**
         * 带检索功能的信息窗
         * @param {Object} content 信息窗文本
         * @param {Object} options 信息窗的可选参数
         */
        searchInfoWindow: function (content, options) {
            options.content = content;
            var infowindow = new AMap.AdvancedInfoWindow(options);
            return infowindow;
        },
        /**
         * 获取信息窗内容
         * @param {Object} infoWindow 信息窗对象
         */
        getWindowContent: function (infoWindow) {
            return infoWindow.getContent();
        },
        /**
         * 多关键字检索
         * @param {Object} myKeys 关键字数组 [string,string,....]
         */
        searchInBounds: function (myKeys) {
            var map = this.map;
            AMap.service(["AMap.PlaceSearch"], function () {
                if (typeof placeSearch == "undefined") {
                    placeSearch = new AMap.PlaceSearch({ //构造地点查询类
                        pageSize: 5,
                        map: map
                    });
                    placeSearch.clear();
                }
                var keyString = "";
                for (var i = 0; i < myKeys.length; i++) {
                    keyString += myKeys[i] + "｜";
                }
                //关键字查询
                placeSearch.search(keyString, function (status, result) {
                    //根据业务需求返回数据
                });
            });
        },
        /**
         * 矩形区域检索
         * @param {Object} pointLeft 左上角的点坐标 地图的Point类型
         * @param {Object} pointRight 右下角的点坐标 地图的point类型
         * @param {Object} key 检索的条件 string类型
         */
        searchInRectangle: function (pointLeft, pointRight, key) {
            var map = this.map;
            AMap.service(["AMap.PlaceSearch"], function () {
                if (typeof rectSearch == "undefined") {
                    rectSearch = new AMap.PlaceSearch({ //构造地点查询类
                        pageSize: 5,
                        pageIndex: 1,
                        map: map
                    });
                }
                //多边形查
                var polygonArr = [//多边形覆盖物节点坐标数组
                    [pointLeft.lng, pointLeft.lat],
                    [pointRight.lng, pointLeft.lat],
                    [pointRight.lng, pointRight.lat],
                    [pointLeft.lng, pointRight.lat]
                ];
                var polygon = new AMap.Polygon({
                    path: polygonArr,//设置多边形边界路径
                    strokeColor: "#FF33FF", //线颜色
                    strokeOpacity: 0.2, //线透明度
                    strokeWeight: 3,    //线宽
                    fillColor: "#1791fc", //填充色
                    fillOpacity: 0.35//填充透明度
                });
                rectSearch.clear();
                rectSearch.searchInBounds(key, polygon);
            });
        },
        /**
         * 圆内区域检索
         * @param {Object} myKeys 检索的条件 string类型
         * @param {Object} centrePoint
         * @param {Object} radius
         */
        searchInCircle: function (myKeys, centrePoint, radius) {
            var map = this.map;
            AMap.service(["AMap.PlaceSearch"], function () {
                if (typeof circleSearch == "undefined") {
                    circleSearch = new AMap.PlaceSearch({ //构造地点查询类
                        pageSize: 5,
                        type: myKeys,
                        pageIndex: 1,
                        map: map
                    });
                }
                circleSearch.clear();
                circleSearch.setType(myKeys);
                circleSearch.searchNearBy('', centrePoint, radius, function (status, result) {

                });
            });
        },
        /**
         * 获得项目路径
         * @return
         */
        getRootPath: function () {
            var curWWWPath = window.location.href;
            var pathName = window.location.pathname;
            var pos = curWWWPath.indexOf(pathName);
            var localhostPath = curWWWPath.substring(0, pos);
            var porejectName = pathName.substring(0, pathName.substring(1).indexOf('/') + 1);
            return (localhostPath + porejectName);
        },
        /**
         * 保存到浏览器
         * @return
         */
        saveLoadData: function (name, value) {
            var storage = window.localStorage;
            if (storage) {
                try {
                    if (value.indexOf('_') < 0) {
                        value = getDistrictVersion() + "_" + value;
                    }
                    storage.setItem(name, value);
                } catch (e) {
                }
            }
        },
        /**
         * 将边界数据上传到后台数据库
         * @return
         */
        uploadMapData: function (name, value) {
            //上传数据
            var url = map.getRootPath() + '/modelattributes/map/insertDistrict.do';
            $.post(url, { jsonStr: getDistrictVersion() + "_" + value, name: name }, function (data) {
                //				//console.info('上传结果:'+JSON.stringify(data));
            });
        },
        /**
         * 将边界数据上传到后台数据库
         * @return
         */
        getStorageData: function (ssName) {
            var str;
            var storage = window.localStorage;
            if (storage) {
                try {
                    str = storage.getItem(ssName);
                } catch (e) {
                }
            }
            if (str) {
                if (str.indexOf('_') < 0) {//说明格式数据不正确，version_[[坐标]]
                    str = '';
                    storage.removeItem(ssName);
                } else {
                    var size = str.substr(0, str.indexOf('_'));
                    if (size != getDistrictVersion()) {
                        str = '';
                        storage.removeItem(ssName);
                    } else {
                        str = str.substr(str.indexOf('_') + 1);
                    }
                }
            }
            return str;

        },
        getStorageDataJson: function (str) {
            if (str.indexOf('_') < 0) {//说明格式数据不正确，version_[[坐标]]
                str = '';
                storage.removeItem(ssName);
            } else {
                var size = str.substr(0, str.indexOf('_'));
                if (size != getDistrictVersion()) {
                    str = '';
                    storage.removeItem(ssName);
                } else {
                    str = str.substr(str.indexOf('_') + 1);
                }
            }
            return str;

        },
        /**
         * 获得坐标数据的抽稀比例
         * @param ssName key名称
         * @return
         */
        getDataCXSize: function (ssName) {
            /**
             * 这个方法需要修改
             */
            var sizeNum = 50;//数据抽取比例
            var length = ssName.length;
            if (ssName.indexOf('bounds_内蒙古自治区') >= 0) {
                length = length - 3;
            } else if (ssName.indexOf('bounds_新疆维吾尔自治区') >= 0) {
                length = length - 5;
            } else if (ssName.indexOf('bounds_广西壮族自治区') >= 0) {
                length = length - 4;
            }
            if (length > 11 && length < 15) {
                sizeNum = 6;
            } else if (length >= 15) {
                sizeNum = 2;
            }
            return sizeNum;
        },
        /**
         * 获得红色抽稀比例
         * @param ssName
         * @return
         */
        getBoderDataCXSize: function (ssName, value) {
            /**
             * 这个方法需要修改   2330439
             */
            var sizeNum = 5;//数据抽取比例
            var length = JSON.stringify(value).length;
            if (length >= 6000000) {
                sizeNum = 20;
            } else if (length >= 1000000) {
                sizeNum = 15;
            } else if (length >= 500000) {
                sizeNum = 5;
            } else if (length >= 100000) {
                sizeNum = 2;
            } else {
                sizeNum = 1;
            }
            if (ssName.indexOf('浙江省') >= 0 || ssName.indexOf('江苏省') >= 0) {
                sizeNum = 12;
            }
            if (ssName.indexOf('上海市') >= 0 && ssName.indexOf('上海市上海市') < 0) {
                sizeNum = 2;
            }
            /**
             if(ssName.indexOf('新疆维吾尔自治区')>=0){
				ssName = ssName.replace('新疆维吾尔自治区','新疆省');
			}else if(ssName.indexOf('内蒙古自治区')>=0){
				ssName = ssName.replace('内蒙古自治区','蒙古省');
			}else if(ssName.indexOf('广西壮族自治区')>=0){
				ssName = ssName.replace('广西壮族自治区','广西省');
			}
             var sizeNum = 50;//数据抽取比例
             var length = ssName.length-1;
             if(ssName.indexOf('省')==length){
				sizeNum = 30;
			}else if(ssName.indexOf('市')==length){
				sizeNum = 20;
			}else if(ssName.indexOf('县')==length){
				sizeNum = 5;
			}else if(ssName.indexOf('乡')==length||ssName.indexOf('镇')==length){
				sizeNum = 2;
			}else{
				if(ssName.indexOf('区')==length){
					sizeNum = 10;
				}else{
					sizeNum=5;
				}
			}
             **/
            return sizeNum;
        },
        /**
         * 保存红色边界边框
         * @param ssName
         * @param e
         * @return
         */
        saveBorderData: function (ssName, e) {
            var bounds = e.districtList[0].boundaries;
            var temp = [];
            var loadTemp = [];//本地存储
            var sizeNum = map.getBoderDataCXSize(ssName, bounds);//抽希比例
            for (var i = 0; i < bounds.length; i++) {
                var pst = [];
                var loadPst = [];
                for (var j = 0; j < bounds[i].length; j = j + sizeNum) {
                    var obj1 = new Array();
                    obj1.push(bounds[i][j].lng);
                    obj1.push(bounds[i][j].lat);
                    loadPst.push(obj1);//本地存储
                    pst.push(bounds[i][j]);//当前使用
                }
                temp.push(pst);
                loadTemp.push(loadPst);
            }
            bounds = temp;
            var loadTempStr = JSON.stringify(loadTemp);
            //上传到服务器
            map.uploadMapData(ssName, loadTempStr);
            //保持到本地
            map.saveLoadData(ssName, loadTempStr);
        },
        /**
         * 获得方法存放值
         * @param 方法名称
         * @return
         */
        getMeMapValue: function (key) {
            return this.meMapValue[key];
        },
        /**
         * 设置方法存放值
         * @param 方法名称
         * @return
         */
        setMeMapValue: function (key, value) {
            this.meMapValue[key] = value;
        },
        /**
         * 清空方法存放值
         * @param 方法名称
         * @return
         */
        removeMeMapValue: function (key) {
            $(this.meMapValue).remove(key);
        },
        /**
         * 删除Marker点
         * @return
         */
        removeOverlay: function (overlay) {
            var objs = overlay;
            if (!(objs instanceof Array)) {
                objs = [overlay];
            }
            this.map.remove(objs);
        },
        getRect: function (arr, json) {

            var minLng = json.minLng;
            var maxLng = json.maxLng;
            var minLat = json.minLat;
            var maxLat = json.maxLat;

            for (var i = 0; i < arr.length; i++) {
                var item = arr[i];
                if (item.lng < minLng) {
                    minLng = item.lng;
                }
                if (item.lng > maxLng) {
                    maxLng = item.lng;
                }
                if (item.lat < minLat) {
                    minLat = item.lat;
                }
                if (item.lat > maxLat) {
                    maxLat = item.lat;
                }
            }


            json = {
                minLng: minLng,
                maxLng: maxLng,
                minLat: minLat,
                maxLat: maxLat
            };
            return json;
        },

        /**
         * 绘制行政区边界 @auther:wangqy
         * @param data 需要绘制的行政区列表
         * @return
         */
        showMapBorder: function (data) {

            var meMap = this;

            var loopCount = 0;
            //console.log(data.length);
            AMap.service('AMap.DistrictSearch', function () {
                var opts = {
                    subdistrict: 0,
                    extensions: 'all',
                    level: 'city'
                };
                GdDistrict = new AMap.DistrictSearch(opts);
                var path = [];
                //初始化重置
                cityRect = {
                    minLng: 9999,
                    maxLng: 0,
                    minLat: 9999,
                    maxLat: 0
                };
                for (var j = 0; j < data.length; j++) {
                    var json = data[j];
                    if (!json.city) {
                        continue;
                    }


                    var style = {
                        map: meMap.map,
                        strokeWeight: json.strokeWeight ? json.strokeWeight : 2,
                        fillOpacity: json.fillOpacity ? json.fillOpacity : 0.7,
                        fillColor: json.fillColor ? json.fillColor : '#FFF',
                        strokeColor: json.strokeColor ? json.strokeColor : '#ff0000'
                    };
                    var boundsKey = "border_" + json.city;
                    if (json.style) {
                        var temp = json.style;
                        for (var key in temp) {
                            style[key] = temp[key];
                        }
                    }
                    if (json.level == 3) {
                        GdDistrict.setLevel('district');
                        opts.level = 'district';
                    } else {
                        GdDistrict.setLevel('city');
                        opts.level = 'city';
                    }
                    var isfinish = 0;
                    if (j == data.length - 1)
                        isfinish = 1;
                    var colorjson = {
                        type: 'json', //共用getSearchData的区分
                        style: style,
                        isfinish: isfinish
                    }
                    this.map.search(json.gdCity, colorjson, json.text, json.dbClickFun, '', '', true, 0);
                }
            });
        },

        /**
         * 根据地区名划边框 谭雪发修改
         * @param name 行政区域名称
         * @param tzmap 地图对象
         * @return
         */
        showMapBorder_bak: function (json) {
            if (!json.city) {
                alert('城市不能为空');
                return;
            }

            var meMap = this;

            var style = {
                map: meMap.map,
                strokeWeight: json.strokeWeight ? json.strokeWeight : 2,
                fillOpacity: json.fillOpacity ? json.fillOpacity : 0.7,
                fillColor: json.fillColor ? json.fillColor : '#FFF',
                strokeColor: json.strokeColor ? json.strokeColor : '#ff0000'
            };
            var boundsKey = "border_" + json.city;
            if (json.style) {
                var temp = json.style;
                for (var key in temp) {
                    style[key] = temp[key];
                }
            }

            AMap.service('AMap.DistrictSearch', function () {
                var opts = {
                    subdistrict: 1,
                    extensions: 'all',
                    level: 'city'
                };
                var GdDistrict = new AMap.DistrictSearch(opts);
                if (json.level == 3) {
                    GdDistrict.setLevel('district');
                    opts.level = 'district';
                } else {
                    GdDistrict.setLevel('city');
                    opts.level = 'city';
                }


                meMap.getCacheBound(boundsKey, json.gdCity, GdDistrict, function (bounds) {
                    if (bounds) {
                        var path = [];
                        var jsonRect = {
                            minLng: 9999,
                            maxLng: 0,
                            minLat: 9999,
                            maxLat: 0
                        };


                        for (var i = 0, l = bounds.length; i < l; i++) {
                            style.path = bounds[i];
                            var polygon = new AMap.Polygon(style);

                            var text = json.text;
                            meMap.polygonAddMouse(text, polygon);
                            meMap.polygonDbclick(polygon, json.dbClickFun, text);

                            jsonRect = map.getRect(bounds[i], jsonRect);

                            //path = path.concat(bounds[i]);

                        }
                        path.push(new AMap.LngLat(jsonRect.minLng, jsonRect.minLat));
                        path.push(new AMap.LngLat(jsonRect.maxLng, jsonRect.maxLat));


                        if (json.callBackFun) {
                            json.callBackFun({ path: path });
                        }
                    }
                });


            });
        },
        getCacheBound: function (ssName, gdCity, GdDistrict, fun) {                                        //setBound的内部调用方法，不作为单独的方法使用
            var meMap = this;
            var storage = window.localStorage;
            var bl = false;
            //var ssName = "bounds_"+text.substr(0,text.indexOf('<'));
            var gdname = ssName.replace('border_', '');

            var bounds = map.getStorageData(ssName);//获得浏览器数据
            if (bounds) {
                //console.log("用浏览器数据------------");
                bounds = meMap.convertJson(bounds);
                bl = true;
                var temp = [];
                for (var i = 0; i < bounds.length; i++) {
                    var dianArray = [];
                    for (var j = 0; j < bounds[i].length; j++) {
                        var dian = new AMap.LngLat(bounds[i][j][0], bounds[i][j][1]);
                        dianArray.push(dian);

                    }
                    temp.push(dianArray);
                }
                bounds = temp;
                /*if(fun){
                 fun(bounds);
                 }*/
            }
            //查询先查询本地数据库，如果本地没有则在查询高德地图
            if (!bl) {
                var url = map.getRootPath() + '/modelattributes/map/searchDistrict.do';
                $.post(url, { name: ssName }, function (dataResult) {
                    var dataResult = meMap.convertJson(dataResult);
                    if (dataResult.result == 'ok') {//查询后台数据库
                        //	console.log("用后台数据库------------");
                        bl = true;
                        bounds = jQuery.parseJSON(map.getStorageDataJson(dataResult.data));
                        map.saveLoadData(ssName, dataResult.data);
                        var temp = [];
                        for (var i = 0; i < bounds.length; i++) {
                            var dianArray = [];
                            for (var j = 0; j < bounds[i].length; j++) {
                                var dian = new AMap.LngLat(bounds[i][j][0], bounds[i][j][1]);
                                dianArray.push(dian);
                            }
                            temp.push(dianArray);
                        }
                        bounds = temp;

                        /*if(fun){
                         fun(bounds);
                         }*/
                    } else {//调用高德地图查询
                        //	console.log("用高德地图查询------------");
                        GdDistrict.search(gdCity, function (status, result) {
                            if (status == 'no_data') {
                                if (fun) {
                                    fun([]);
                                }
                            } else {
                                bounds = result.districtList[0].boundaries;
                                meMap.saveBorderData(ssName, result);

                                /*if(fun){
                                 fun(bounds);
                                 }*/
                            }

                        });
                    }

                });
            }

            return bounds;

        },
        disableDoubleClickZoom: function () {
            this.map.setStatus({ doubleClickZoom: false });
        },
        /**
         *显示闪烁点
         *data 坐标点的二维数组
         */
        showFlashingPoint: function (data) {
            if (!data || !data.length) {
                alert("请传递有效的点集合！")
                return;
            }
            this.map.setMapStyle('dark');
            var This = this;
            this.map.plugin(['AMap.CustomLayer'], function () {
                rs = data;
                for (var i = 0, len = rs.length; i < len; i++) {
                    var lnglat = new AMap.LngLat(rs[i][0], rs[i][1]);
                    rs[i].containerPos = This.map.lngLatToContainer(lnglat);
                    rs[i].radious = Math.max(2, Math.floor(Math.random() * 10));

                    var s = new Star({
                        x: rs[i].containerPos.x - rs[i].radious,
                        y: rs[i].containerPos.y - rs[i].radious,
                        size: rs[i].radious
                    });
                    stars.push(s);
                }
                canvas = document.createElement('canvas');
                canvas.width = This.map.getSize().width;
                canvas.height = This.map.getSize().height;
                var cus = new AMap.CustomLayer(canvas, {
                    zooms: [3, 8],
                    zIndex: 12
                });
                cus.render = function () {
                    This.onRender(This)
                };
                cus.setMap(This.map);
            });
        },
        /**
         * 内部方法,供闪烁点调用,地图重绘时触发此函数
         */
        onRender: function (This) {
            for (var i = 0; i < rs.length; i += 1) {
                var lngLat = new AMap.LngLat(rs[i][0], rs[i][1]);
                rs[i].containerPos = This.map.lngLatToContainer(lngLat);
            }
            This.draw();
            if (!started) {
                This.autoSize(This);
                started = true;
            }
        },
        /**
         * 内部方法,供闪烁点调用
         */
        draw: function () {
            var ctx = canvas.getContext('2d');
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            stars.length = 0;
            for (var i = 0; i < rs.length; i++) {
                var s = new Star({
                    x: rs[i].containerPos.x - rs[i].radious,
                    y: rs[i].containerPos.y - rs[i].radious,
                    size: rs[i].radious
                });
                stars.push(s);
            }
            for (var i = 0; i < stars.length; i++) {
                stars[i].render(i);
            }
        },
        autoSize: function (This) {
            This.draw();
            setTimeout(function () {
                This.autoSize(This);
            }, 250);
        },
        /**
         *
         * @param json
         * json.eventType  事件类型
         * json.targetObj  目标对象
         * json.callBackFun回调方法
         * @return
         */
        addObjListener: function (json) {
            if (!json || !json.targetObj) {
                return "参数不全";
            }
            if (!json.eventType) {
                json.eventType = "click";
            }
            AMap.event.addListener(json.targetObj, json.eventType, function (data) {
                data.currentTarget = data.target;
                if (data.lnglat) {
                    data.clickPoint = { lng: data.lnglat.lng, lat: data.lnglat.lat };
                    data.point = { lng: data.target.getPosition().lng, lat: data.target.getPosition().lat };
                }

                if (json.callBackFun && typeof json.callBackFun === "function") {
                    json.callBackFun(data);
                } else if (json.callBackFun) {
                    window[json.callBackFun](data);
                }
            });
        },
        /**
         * 计算两点间距离  单位：米
         * @param startPoint
         * @param endPoint
         * @return
         */
        getDistance: function (startPoint, endPoint) {
            var value = startPoint.distance([endPoint.lng, endPoint.lat]);
            if (value != 0) {
                value = value.toFixed(2);
            }
            return value;
        },

        calcMinu: function (start, end) {
            return (end.getTime() - start.getTime()) % (24 * 3600 * 1000) % (3600 * 1000) % (60 * 1000)
        },
      //关闭信息框
        closeInfoWindow: function () {
            this.map.closeInfoWindow();
        },
        addMapTypeControl: function () {
            var myMap = this.map;
            myMap.plugin(["AMap.MapType"], function () {
                var mapType = new AMap.MapType({defaultType: 0,showRoad:false});
                myMap.addControl(mapType);
            });
        }

    };

    /**
     * 地图子类
     */
    MapCore.Point = function (arr) {														//点类
        return new AMap.LngLat(arr[0], arr[1]);
    };
	MapCore.MyLabel = function(thml,opt){				
		var obj = {
				  text:thml,
				  position:opt.position
				  };
				 return new AMap.Text(obj);
	};
    MapCore.Icon = function (options) {														//点类
        return new AMap.Icon(options);
    };
    MapCore.Pixel = function (arr) {															//像素类
        if (2 == arguments.length) {
            return new AMap.Pixel(arguments[0], arguments[1])
        } else if (1 == arguments.length) {
            return new AMap.Pixel(arr[0], arr[1]);
        }
    };
    MapCore.Size = function (arr) {														//size类
        if (2 == arguments.length) {
            return new AMap.Size(arguments[0], arguments[1])
        } else if (1 == arguments.length) {
            return new AMap.Size(arr[0], arr[1]);
        }
    };
    MapCore.Marker = function (point) { 	 												 //点类
        var voffset = new AMap.Pixel(0, 0); //默认不偏移

        //因为amap的setoffset方法不好用
        //用opt属性区分是传的参数列表还是一个position的point
        var marker;
        if (point.autoOptions != undefined && point.autoOptions == 1) {
            if (point.offset != undefined) {//根据offset数值直接设置偏移量
                voffset = point.offset;
            } else if (point.iconsize != undefined && point.offsettag != undefined) {
                //根据offsettag和图标大小设置偏移量
                voffset = map.getOffsetOfTag(point.iconsize, point.offsettag);
                //oftag这个方法和mass海量点的anchor共用，anchor和offset同样以图片左上角点为定点，但是anchor为绝对值，offset为具体偏移数值
                //故而获得的offset是anchor的width和height进行取负数
                voffset.x = (0 - voffset.x);
                voffset.y = (0 - voffset.y);
                //console.log("offset:" + voffset.x + "," + voffset.y);
            } else {
                //	console.log("未获取到正确的偏移量参数，采用不偏移形式绘制图标！");
            }
            marker = new AMap.Marker({
                position: point.point,
                offset: voffset
            });
            //如果在构造参数里设置icon而不是用setMarkerIcon的方法,则在此进行设置
            if (point.icon != undefined) {
                point.icon.size = point.iconsize;
                marker.setIcon(point.icon);
            }
        } else { //兼容老方法...
            marker = new AMap.Marker({ position: point });
        }

        marker.addEvent = function (type, fn) {											//marker事件
            AMap.event.addListener(this, type, fn);
        };
        marker.setInfoWindow = function (content) {										//marker聚合
            AMap.event.addListener(this, "click", function () {
                var infoWindow = new AMap.InfoWindow({ content: content });
                infoWindow.open(this.getMap(), this.getPosition());
            });
        };
        return marker;
    };

    MapCore.NavigationControl = function (tzmap) {														//自定义控件
        return new AMap.NavigationControl({
            type: AMAP_NAVIGATION_CONTROL_SMALL
        });
    };
    var rs, started, canvas, stars = [];

    function Star(options) {
        this.init(options);
    }

    Star.prototype.init = function (options) {
        this.x = ~~(options.x);
        this.y = ~~(options.y);
        this.initSize(options.size);
        if (~~(0.5 + Math.random() * 7) == 1) {
            this.size = 0;
        } else {
            this.size = this.maxSize;
        }
    }
    Star.prototype.initSize = function (size) {
        var size = ~~(size);
        this.maxSize = size > 6 ? 6 : size;
    }
    Star.prototype.render = function (i) {
        var p = this;
        if (p.x < 0 || p.y < 0 || p.x > canvas.width || p.y > canvas.height) {
            return;
        }

        var ctx = canvas.getContext('2d');
        ctx.beginPath();
        var gradient = ctx.createRadialGradient(p.x, p.y, 0, p.x, p.y, p.size);
        gradient.addColorStop(0, "rgba(7,120,249,1)");
        gradient.addColorStop(1, "rgba(7,120,249,0.3)");
        ctx.fillStyle = gradient;
        ctx.arc(p.x, p.y, p.size, Math.PI * 2, false);
        ctx.fill();
        ctx.closePath();
        if (~~(0.5 + Math.random() * 7) == 1) {
            p.size = 0;
        } else {
            p.size = p.maxSize;
        }
    }
    a.Star = Star;
    a.MapCore = MapCore;																//完成类库封装

})(window);